jekaterina jekaterina - 14 days ago 5
HTML Question

Jquery selector select a h4 tag under a div

I want to change the text in h4 tag to the class name of its grandparent div i.e. (sds 2016 gwap).

<div class="grid">
<div class="office-year-function sds 2016 gwap">
<div class="content cell-child">
<img src="535/img/01.jpg" alt="" width="312px" height="160px">
</div>
<div class="img-hover cell-child">
<br/>
<h3>GWAP Kick-off Ceremony</h3>
<h3>2016</h3>
<h4></h4>


When the document finishes loading, it will run the below function.

function changeTag() {
for (var i = 1; i <= $('.office-year-function').length; i++) {
$this = $('div.grid div.office-year-function:nth-child(' + i + ')');
var className = $this.attr('class');
className = className.split(" ");

for (var j = 1; j < className.length; j++) {
className[j] = className[j].replace("-", " ");

if (className[j] == "gwap") {
$this.find("h4").html += className[j].toUpperCase();
} else {
$this.find('h4').html += className[i].capitalize();
}
}
}

}


But there's errors in

$this.find("h4").html+=className[j].toUpperCase();
$this.find('h4').html+=className[i].capitalize();


What's wrong with my code?

Answer

You current implementation doesn't work as .html() is a function, you are treating as property. You can use [0] to get the underlying DOM element and the use innerHTML property.

 $this.find("h4")[0].innerHTML +=className[j].toUpperCase();

However, use .append() can be used to get the desired result.

function changeTag() {
    for (var i = 1; i <= $('.office-year-function').length; i++) {
        $this = $('div.grid  div.office-year-function:nth-child(' + i + ')');
        for (var j = 1; j < className.length; j++) {
            className[j] = className[j].replace("-", " ");
            if (className[j] == "gwap") {
                $this.find("h4").append(className[j].toUpperCase());
            } else {
                $this.find("h4").append(className[i].capitalize());
            }
        }
    }
}