Brian
Brian

Reputation: 616

Is it possible to have javascript ignore a specific section of my html

I have a script that executes on every page of my website. I still want it to execute on the page in question but just to ignore a section.

E.g.

<p>process with javascript</p>
<p>skip, have javascript function ignore</p>
<p>process with javascript</p>

If there is an inline tag or something that would be what i am looking for. E.g.

<p>process with javascript</p>
<script-ignore><p>skip, have javascript function ignore</p></script-ignore>
<p>process with javascript</p>

Upvotes: 1

Views: 1511

Answers (3)

A. El-zahaby
A. El-zahaby

Reputation: 1170

in my opinion the best way, is using not in the selector

$('p:not(.js-ignore)') // ignore the section by class "js-ignore"
  .css('background','blue') //whatever your code dose
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<p>process with javascript</p>
<p class='js-ignore'>skip, have javascript function ignore</p>
<p>process with javascript</p>

by your way i believe you can do something like this:

$( "p" ).each(function() {
  if(!$(this).parents('script-ignore').length){
    $(this).css('background','blue')
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<p>process with javascript</p>
<script-ignore><p>skip, have javascript function ignore</p></script-ignore>
<p>process with javascript</p>

Update 1

i realise you didn't mention 'jquery' so this is pure vanilla JS:

var p = document.querySelectorAll('p'); // select

for( i=0; i< p.length; i++ ){
  if(p[i].parentElement.localName !== 'script-ignore'){
    // whatever your code is
  	p[i].style.background = 'red'
  	p[i].style.color = '#fff'
  }
}
<p>process with javascript</p>
<script-ignore><p>skip, have javascript function ignore</p></script-ignore>
<p>process with javascript</p>

Upvotes: 3

Muhammed Nigil
Muhammed Nigil

Reputation: 183

<p>process with javascript</p>
<p class="dontIncludeJavascriptCall">skip, have javascript function ignore</p>
<p>process with javascript</p>
var ps = document.querySelectorAll("p:not(.dontIncludeJavascriptCall)");
console.log(ps);

This will only give you the 2 P tags which do not have that class

Upvotes: 3

OmmiZone
OmmiZone

Reputation: 76

Try put a class name class="useJS" in your p tag that use JavaScript.

Then point your script to .useJS class only.

Upvotes: 0

Related Questions