简体   繁体   中英

How to append content in javascript using innerHTML

I want to display content in a div whose id is search_result, I am using following code but it is only showing the last element of the array because of innerHTML. Can anyone help me to append the data.

here is my JavaScript code

function myFunction($qw) {
    for ($i = 0; $i < data.length; $i++) {
        $dis = data[$i].charAt(0);
        var $n = ($dis.localeCompare($qw))
        if ($n == 0)
            document.getElementById("search_result").innerHTML = (data[$i] + "<br/>");
    }
    $i = 0;
}

Here is my HTML code :

<div id="search_result">
</div>

You're replacing the content of the div with every step in your for.. loop .

function myFunction($qw)
        {
    //set  a var
    var new_content;
        for($i=0;$i<data.length;$i++){
        $dis = data[$i].charAt(0);
        var $n = ($dis.localeCompare($qw))
        if($n == 0)
    //remove replacing the innerHTML here
    //instead, add content to the variable
        new_content+=data[$i] + "<br/>";
        }

    //replace content of div after the loop
    document.getElementById("search_result").innerHTML=new_content;
        $i=0;
        }

It is not a good practice to touch DOM on every change. I'd better do this way:

function myFunction($qw) {
  var display = [];
  var $dis;
  var $n; 
  for (var $i = 0; $i < data.length; $i++) {
    $dis = data[$i].charAt(0);
    $n = ($dis.localeCompare($qw))
    if ($n == 0)
        display.push(data[$i]);
  }
  $i = 0;
  document.getElementById("search_result").innerHTML = display.join('<br />');
}

Or fancy way

function myFunction($qw) {
  var display = data.filter(function (el) {
    var $dis = el.charAt(0);
    var $n = $dis.localeCompare($qw);
    return $n === 0;
  });
  document.getElementById("search_result").innerHTML = display.join('<br />');
}

Also use var statement to initialize variables

Just to add to @Sachin's answer, cache the string and then add it entirely to the dom afterwards:

function myFunction($qw) {
    var str = '';
    for ($i = 0; $i < data.length; $i++) {
        $dis = data[$i].charAt(0);
        var $n = ($dis.localeCompare($qw))
        if ($n == 0)
            str += (data[$i] + "<br/>");
    }
    document.getElementById("search_result").innerHTML = str;
    $i = 0; 
}

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