xEe
xEe

Reputation: 165

run javascript only for specific div/s

How I can run for example this javascript only for specific div/s. Thanks

var getAllAnchorTags = document.querySelectorAll('a');
getAllAnchorTags.forEach(function(item){
 var creatLink =item.getAttribute('href')+item.textContent;
 item.setAttribute('href',creatLink)
})

in this case for all divs inside wrap div

<div id=wrap>
 <div id=tab1>...</div>
 <div id=tab2>...</div>
</div>

Upvotes: 0

Views: 3966

Answers (3)

Jordan Georgiadis
Jordan Georgiadis

Reputation: 331

with jquery you can reference to subdivs of specific div, with a way like this

$('#wrap').find('div').each(function(){
    var innerDivId = $(this).attr('id');
    alert(innerDivId)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<div id=wrap>

wrap

 <div id=tab1>one</div>
 <div id=tab2>two</div>
</div>

Upvotes: 0

Gianluca Paris
Gianluca Paris

Reputation: 1429

querySelector and querySelector accepts all CSS Selectors that you can use as CSS rules.

So to select only as that are decsendants of #tab1 use this:

var getAllAnchorTags = document.querySelectorAll('#tab1 a');

Upvotes: 3

AP.
AP.

Reputation: 8921

You can filter your js code based on the div's you want by assigning them some selector class (ex. divs-to-work-on).

var getAllAnchorTags = document.querySelectorAll('.divs-to-work-on a');
getAllAnchorTags.forEach(function(item) {
  var creatLink = item.getAttribute('href') + item.textContent;
  item.setAttribute('href', creatLink)
})
<div id=wrap>
  <div id=tab1 class='divs-to-work-on'>...</div>
  <div id=tab2>...</div>
  <div id=tab3 class='divs-to-work-on'>...</div>
</div>

Now your code will only apply to divs that have the class divs-to-work-on.

Upvotes: 1

Related Questions