Reputation: 39
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?
Upvotes: 2
Views: 1913
Reputation: 3820
I would suggest to use .text(text) of jquery instead of .append() for following, choice is yours.
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").text(className[j].toUpperCase());
} else {
$this.find("h4").text(className[i].capitalize());
}
}
}
}
As per documentation : http://api.jquery.com/append/
.append() is used when you are dealing with DOM elements.
As per your current requirement you only need to update content of h4 tag to the class name of grandparent div.
So, text(text) would suffice.
Set the content of each element in the set of matched elements to the specified text.
Upvotes: 0
Reputation: 133423
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());
}
}
}
}
Upvotes: 1