简体   繁体   中英

looping through <article> in the html page

I have to loop through <article> tag in the Html file and add its classname when clicked and then remove the class name in all other <article> tags

for eg:

 <article onclick="javascript:selectthis(this)">
1
</article>
<article onclick="javascript:selectthis(this)">
11
</article>
<article onclick="javascript:selectthis(this)">
111
</article>
<article onclick="javascript:selectthis(this)">
1111
</article>
<article onclick="javascript:selectthis(this)">
11111
</article>

<script>
function selectthis(THIS) {

 THIS.className = "countrySelected";

  }
</script>

is there a way to loop through the tags and remove the classnames except for the recent one that is clicked? What is the best possible way to do ? Should I really have to add a onclick event attached to every <article> tag? because there could be many <article> tag in the html file. I really donot want to add this onclick event to every article tag.

any help would be appreciated.

You didn't tag jQuery , but I'd recommend using that in this particular case, where event bubling and filtering plays nice. Instead of register multiple click-handlers (as you point out) you can register one soley, and have that one in common for all elements. jQuery is good at filtering out events to a specific selector as well. I'd give it a shot.

Here's an example of how to solve your issue using jQuery:

// Register an event-handler on document, that listens for a 'click' event.
// Only pick up the event from the selector 'article' though, which corresponds
// to only article elements on the page.
$(document).on('click', 'article', function(){
    this.className = "countrySelected"; // this in this context, is the actual DOM-element
});

Then for your issue of removing the className for all articles, not having the class countrySelected . This also is nice with jQuery as such:

// Find all article-elements, that DON'T have the class countrySelected
// Then remove _all_ the classes it has
// To remove a specific class, use .removeClass('classToRemove')
$('article').not('.countrySelected').removeClass();

So in the end, you can combine the two and make this:

$(document).on('click', 'article', function(){
    $('article').removeClass(); // Remove class from all other first
    this.className = "countrySelected"; // this in this context, is the actual DOM-element
});

Add this jquery:

$("article").click(function() {
  $("article").toggleClass("countrySelected");
});

Example code snippet:

 $("article").click(function() { $(".countrySelected").removeClass("countrySelected"); $(this).addClass("countrySelected"); }); 
 article.countrySelected { background-color: orange; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <article>This is article 1</article> <article>This is article 2</article> <article>This is article 3</article> <article>This is article 4</article> <article>This is article 5</article> <article>This is article 6</article> 

Since you didn't tag this jquery, here is a pure javascript solution:

window.onload = function() {
  // This is a list of all the articles on the page
  var articles = document.querySelectorAll("article");
  for (var i = 0; i < articles.length; ++i) {
    // Loop through each article
    var article = articles[i];
    // Add an event listener for each one
    article.addEventListener("click", function() {
      // Get the previously selected one and deselect it
      var prevSelected = document.querySelector(".countrySelected");
      if (prevSelected != null) prevSelected.classList.remove("countrySelected");
      this.classList.add("countrySelected"); // or for older browsers: this.className = "countrySelected";
    }, false);
  }
}

 window.onload = function() { var articles = document.querySelectorAll("article"); for (var i = 0; i < articles.length; ++i) { var article = articles[i]; article.addEventListener("click", function() { var prevSelected = document.querySelector(".countrySelected"); if (prevSelected != null) prevSelected.classList.remove("countrySelected"); this.classList.add("countrySelected"); // or for older browsers: this.className = "countrySelected"; }, false); } } 
 .countrySelected { background-color: orange; } 
 <article>Article 1</article> <article>Article 2</article> <article>Article 3</article> <article>Article 4</article> <article>Article 5</article> 

Assuming you do place an onclick on each article .. inside of your function, you could do this:

function selectthis(THIS) {

    //remove the css classes from all articles
    var articles=document.getElementsByTagName('article');
    for(var a=0;a<articles.length;a++){
        articles[a].setAttribute('class','');
    }

    //add class back on for this article
    THIS.className = "countrySelected";
}

I'll treat it this way without using jQuery. The reason why is this way in the future it is far more easier to understand why certain stuff happens. And sometimes basic JS is far more fitting for using a small adjustment instead of a bloated library.

The best way is to start, is at the moment nothing still happened and the page just loaded. Instead of using the javascript inline with an onclick. First assign an event-listener.

Page Loaded

With Element.getElementsByTagName() you can get all the needed elements and go for a loop. documentation ;

So you get

var articleTags = document.getElementsByTagName('ARTICLE');

In this case we can use a simple loop

var articleDOM = null;
for(var i = 0; i < articlesTags.length; i++){
    articleDOM = articlesTags[i];
    articleDOM.addEventListener("click", addClassToArticleFunction);
)

Each article now has an event binded with a function. Let's define that function.

Add Class Function

I'll use ' addClassToArticleFunction ', but you can of course make it even more generic in name. Could be you want also use this function for other tags or DOM-elements.

function addClassToArticleFunction(){
    this.className = "countrySelected";

}

Each time this will be called the class will be defined. Only you off course get a problem by all of them will get that classname.

So lets just call a function that will do all the deleting.

function addClassToArticleFunction(){
    deleteClassNameFromArticles();
    this.className = "countrySelected";
}


function deleteClassNameFromArticles(){
     //deletion here
}

Since we know all the articles already, and know how to calls the classname it is an easy copy paste

for(i = 0; i < articleTags.length; i++){
    articleDOM = articleTags[i];
    articleDOM.className = "";
}  

At this point it is done.

Recap

  • load window
  • assign event listeners to articles
  • when clicked on article a function will be called
  • this function will delete all classnames from articles
  • this function will assign on the clicked article a classname

JS fiddle to see it work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM