Replace innerHTML of divs with same class based on content - javascript

I am trying to only replace the content of the div with the "replace this".
The content of each div is dynamically created, so i have to check which class needs to be changed. I tried it with a for-loop and so far I am getting the right div but having trouble changing its content. The main problem is that they all have the same class. How can I put the new text into the correct div without changing the others?
var x = document.getElementsByClassName("class_name");
var teststring = "rep";
for (i = 0; i < x.length; i++) {
if (x[i].toString().indexOf(teststring) > 0) {
this.innerHTML = "text3";
}
}
<div class="class_name">
text1
</div>
<div class="class_name">
text2
</div>
<div class="class_name">
replace this
</div>

Declare the variable with let in the for loop which will create it's own scope within curly braces ({...}). Instead of using this, use the current element with x[i]. x[i] refers to the element itself, you have to take the content from it.
I will prefer textcontent instead of innerHTML
var x = document.getElementsByClassName("class_name");
var teststring = "rep";
for (let i = 0; i < x.length; i++) {
if (x[i].textContent.indexOf(teststring) > 0) {
x[i].textContent = "text3";
}
}
<div class="class_name">
text1
</div>
<div class="class_name">
text2
</div>
<div class="class_name">
replace this
</div>

Use x[i].innerHTML not this.innerHTML
var x = document.getElementsByClassName("class_name");
var teststring = "rep";
for (i = 0; i < x.length; i++) {
if(x[i].innerHTML.indexOf(teststring) !== -1) {
x[i].innerHTML = "text3";
}
}
DEMO
https://jsfiddle.net/0cmz4pvk/5/

Related

How to add ID to <a href> on click using JavaScript

I have an HTML like this
How add ID to HTML href with javascript
<div class="tab">
exp
</div>
<div class="tab">
exp
</div>
<div class="tab">
exp
</div>
<script>
var els = document.getElementsByClassName("tab");
// loops els
for(var i = 0, x = els.length; i < x; i++) {
els[i].onclick = function(){
x = document.querySelector(".tab> a")
// do something
x.id = "expid";
}
}
</script>
I want to add the id to each tag when I click this. Pls help me. Thks so much
<div class="tabs">
... your html code.
</div>
const tabs = document.querySelector('.tabs')
tabs.addEventListener('click', event => {
const aTag = event.target
if (aTag.tagName !== 'A') return
aTag.id = `EXPID#${getIndexIn(aTag, tabs)}`
})
function getIndexIn(element, parent): number
What's the meaning to be it?
Your call to document.querySelector() always returns the first .tab > a link in the document. You can this.querySelector() to return the link in the DIV that you clicked on instead.
I've changed the code to use a class rather than ID, since you shouldn't have duplicate IDs.
Loop through all the DIVs. If it's the DIV that the user clicked on, add the class, otherwise remove it.
var els = document.getElementsByClassName("tab");
// loops els
for (var i = 0, x = els.length; i < x; i++) {
els[i].onclick = function() {
for (var j = 0; j < els.length; j++) {
x = els[j].querySelector("a");
if (els[j] == this) {
x.classList.add("expid");
} else {
x.classList.remove("expid");
}
}
}
}
.expid {
background-color: yellow;
}
<div class="tab">
exp
</div>
<div class="tab">
exp
</div>
<div class="tab">
exp
</div>
const anchors = document.getElementsByTagName('a');
const ids= [1,2,3,4,5];
let index =0 ;
for(let a of anchors ){
a.href=ids[index++]
}
you can try this way it's a cool and easiest what I do with pure js

why `card` element is not duplicated 4 times

Why is card element not duplicated 4 times?
function generate4Cards() {
for (var i=0; i < 4; i++) {
var card = document.getElementById('card');
document.body.appendChild(card);
}
}
<body onload="generate4Cards()">
<div id="card">I am a card</div>
</body>
When you call appendChild with an existing element, that element will be removed from its former position in the DOM and appended to the new container. You'll have to explicitly create the div on each iteration instead.
But, having duplicate IDs in a single document is invalid HTML, so probably best to remove the id (or use a class instead):
for (var i = 0; i < 4; i++) {
var card = document.createElement('div');
card.textContent = 'I am a card';
document.body.appendChild(card);
}
Another option is to use cloneNode:
var originalCard = document.querySelector('div');
for (var i = 0; i < 4; i++) {
var card = originalCard.cloneNode(true);
document.body.appendChild(card);
}
<div>I am a card</div>
foo.append(bar) puts bar at the end of foo.
If I put my car at the end of my road, and then put my car at the end of my drive then I don't have two cars.
append only puts bar where you tell it to put it.
It doesn't duplicate it because it isn't supposed to.
Here is the sample code you are looking for -
<html>
<head>
<script>
function generate4Cards() {
for (var i = 0; i < 4; i++) {
var card = document.createElement('div');
card.textContent = 'I am a card';
document.getElementById('cardHolder').appendChild(card);
}
}
</script>
</head>
<body onload="generate4Cards()>
<div id="cardHolder"></div>
</body>
</html>

How scan all <span> tags of a page and get or set a content?

I have this following code that scans all <input> tags of a page and then you are able to set you to get a value to this tag.
var input = document.getElementsByTagName('input');
for (var i = 0; i < input.length; i++) {
input[i].value = "123";
}
Now, how can I do the same with a <span> tag, which I already know does not have a property called value?
Your question was somewhat confusing, but I'll give my best answer:
Just take your code for the inputs, and change a few key componenents:
var span = document.getElementsByTagName('span');//Replace "input" with "span"
for (var i = 0; i < span.length; i++) {//Again, replacing "input" with "span"
var textInsideTheSpan = span[i].textContent;//Reading text inside span
span[i].textContent = "Your text here";//Writing text to the span
}
The key here is in the .textContent, a property of the javascript Node object, which can be read or written to, depending on your application. Everything else simply replaced "input" with "span".
Just use following:
var spans = document.getElementsByTagName('span');
for (var i = 0; i < spans.length; i++) {
var text = spans[i].innerHTML;
if (text.length == 0) {
spans[i].innerHTML = i; //Some text
}
}
You can use Node.textContent to set the text inside span:
var input = document.getElementsByTagName('span');
for (var i = 0; i < input.length; i++) {
input[i].textContent = "123";
}
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>

Select all element with same tag name using javascript and highlight content partially

I made a code that should highlight searched string but it is not working.
Here is the code:
<body>
<div>div is here</div>
<div id="divid">
<div>this is a div 1</div>
<div> this is a div 2</div>
<div> this is a div3</div>
</div>
<div> another div is here</div>
</body>
Here is a javascript code.
function checkit(){
var hlWord = "div";
var nregex = new RegExp(hlWord,"gi");
var div = document.getElementById("divid").getElementsByTagName('div');
for(var i=0; i <= div.length; i++){
var div1 = div[i].innerHTML;
var rword = div1.replace(nregex,"<b>"+hlWord+"</b>");
div1.innerHTML = rword;
}
}
There are begginer mistakes in your code. Let me correct them:
function checkit(){
var hlWord = "div"; //Define string that will be emphasized by <b> tag
var nregex = new RegExp(hlWord,"gi");//Create global, case-insensitive regexp
var div = document.getElementById("divid").getElementsByTagName('div'); //Get element collection of divs in div#divid
for(var i=0; i < div.length; i++){ //Loop through my element collection
var div1 = div[i].innerHTML; //Get the innerHTML of on of the divs
var rword = div1.replace(nregex,"<b>"+hlWord+"</b>"); //Surround my string with <b>
div[i].innerHTML = rword; //Change the innerHTML back
}
}
You used this for condition: i<=div.length. This is wrong. Do not forget, that we count from 0 so: [0, 1, 2, 3].length = 4. Last element for such array has index 3. The [] is an array literal.
By mistake, you assigned div1.innerHTML. div1 was a string. The element you want to change is div[i].
I made a JSFiddle too!
The problem with you code will be, amongst other problems, that nested div elements will be broken. You should use some kind of recursion if you want to highlight the word 'div'.
Here is such a function:
function highLight(term,root){
var allDiv = root.querySelectorAll('div'),
replacer = function(a){return '<span class="highlight">'+a+'</span>'};
for (var i=0; i<allDiv.length; i+=1){
if (allDiv[i].querySelectorAll('div').length){
highLight(term, allDiv[i]);
} else {
var re = RegExp('('+term+')','gi');
allDiv[i].innerHTML = allDiv[i].innerHTML.replace(re,replacer);
}
}
}
And here is a jsfiddle to play around with it
A more advanced jsfiddle
You have several errors: there you go:
http://jsfiddle.net/55U6j/1/
function checkit(){
var hlWord = "div";
var nregex = new RegExp(hlWord,"gi");
var divs = document.getElementById("divid").getElementsByTagName('div');
for(var i=0; i < divs.length; i++){
var div = divs[i];
var html = div.innerHTML;
var rword = html.replace(nregex,"<b>"+hlWord+"</b>");
div.innerHTML = rword;
}
}

How to fill a div with content under the condition that the div has no childs?

For example, when I have:
<div class="abc123"></div> <!-- no child div -->
I want to insert a new div in it:
<div class="xyz">some content</div>
So that the outcome is:
<div class="abc123">
<div class="abc">Some Content</div>
</div>
How can I implement this using javascript?
in jQuery:
$(".abc123").each(function() {
if (this.children(".abc").length == 0) {
$(this).append('<div class="xyz">some content</div>');
}
});​
in Simple JS
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
if (divs[i].childNodes.length == 0) { // testing if it has not child
var newdiv = document.createElement('div');
newdiv.innerHTML = "some content";
newdiv.className = "xyz";
divs[i].appendChild(newdiv);
}
}​
Edit:
This following piece of code produces the same effect as done in the above mentioned jQuery code(edited in light of the comment by RobW ):
var divs = document.getElementsByClassName("abc123");
for (var i = 0; i < divs.length; i++) {
if (divs[i].getElementsByClassName("abc").length == 0) {
var newdiv = document.createElement('div');
newdiv.innerHTML = "some content";
newdiv.className = "xyz";
divs[i].appendChild(newdiv);
}
}​
Maybe you would like to take a look at this question: How to check if element has any children in Javascript?
Seems like what you are looking for :)
With jQuery:
if ($('.abc123 div').length == 0) {
$('.abc123').append('<div class="xyz">some content</div>');
}​

Categories