How to access the class of an element which is in variable - javascript

I have a HTML code in variable I want to access the class of that
var test = `
<h2 class= "text">Hello
</h2>`
This is what I try to access the class of attribute and change the color
var query = document.querySelectorAll(".text")
document.getElementById(`${query}`).style.color= red;
I want to access the class of <H2> tag and in change the color.
Have any way to do that?

If you want to modify the string before you add it to the html page.
var test = `
<h2 class= "text">Hello
</h2>`
test = $(test).css("color", "red")
Demo
var test = `
<h2 class= "text">Hello
</h2>`
test = $(test).css("color", "red")
$("body").append(test)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

query is an array, and to get the 1st (only) one, just do query[0].style.color = red;
The reason it's an array is because document.querySelectorAll() returns an array of elements.
But element MUST be in the DOM

Updating my answer now I realise your HTML is in a string. Not sure why you're doing it this way but I digress.
You just include inline styling within your string.
var test = `<html>
<head>
<body>
<h2 style="color: red;" class="text">Hello
</h2>
</body>
</head>
</html>`

Related

HTML Son element can't rewrite its property if father element has put property onto it

When I first write the first version, world is still blue. When I modify it to second version, world doesn't turn blue.
The first version use class="Class on the father element, so that son elements can all use this property. But I want to modify son element's property. It turns out that modification doesn't work as expected.
Then I tried second version. Instead of putting class="Class" on the <div> tag, I use class="Class on each son element. At this time, the modification worked.
null means color still follows original set property in css file.
unset means clear this property value and set it to default value.
CSS file as follows:
.Class {
color: blue;
}
HTML:
first version
<div class="Class">
<h1>hello</h1>
<h1 id="hello">hello</h1>
<h1 id="world">world</h1>
<script>
let hello = document.querySelector("#hello");
let world = document.querySelector("#world");
hello.style.color = null;
world.style.color = "unset";
</script>
</div>
second version
<div>
<h1 class="Class">hello</h1>
<h1 id="hello" class="Class">hello</h1>
<h1 id="world" class="Class">world</h1>
<script>
let hello = document.querySelector("#hello");
let world = document.querySelector("#world");
hello.style.color = null;
world.style.color = "unset";
</script>
</div>
For the sake of convenience, we usually choose the first version, because it doesn't need to add class="Class" on every son element tag. However, it will cause the problem mentioned above. Why the problem arises? And is there other way to still use class="Class" on the father element, and can change son element's property.
The second version can be modified as following in order to have the text colour on world as blue:
<div>
<h1 class="Class">hello</h1>
<h1 id="hello" class="Class">hello</h1>
<h1 id="world" class="Class">world</h1>
<script>
let hello = document.querySelector("#hello");
let world = document.querySelector("#world");
hello.style.color = null;
</script>
</div>
Setting world.style.color = "unset"; in first case was setting #world element colour to the inherited color value from parent, which was blue.
The initial value for color property is expected to be black, which is what setting color to unset in the second case would apply.
Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/unset
use the keyword initial instead of unset to achieve what you want.
let hello = document.querySelector("#hello");
let world = document.querySelector("#world");
hello.style.color = null;
world.style.color = "initial";
.Class{
color:blue;
}
<div class="Class">
<h1>hello</h1>
<h1 id="hello">hello</h1>
<h1 id="world">world</h1>
</div>

Javascript: replace text inside <div>foo <span>text </span>bar</div> by <div>foo text bar</div>

Just as the title suggests, lets consider the following html snippet:
<html>
<body>
<div>foo <span>text </span>bar</div>
</body>
</html>
I would like to transform it by removing the span tags, but keeping the text they contain in the same location, such as
<html>
<body>
<div>foo text bar</div>
</body>
</html>
I would like to do that in javascript. Because this task is (I suppose) uncommon (I am in fact trying to build a GUI for marking data for NLP) I could not really find a solution browsing SO or Google... And I am very new to javascript so I didn't really know where to start.
Aditional question:
If one know how to resolve the first question, maybe can quickly mention how to perform the same transformation on all document span, such as the following document:
<html>
<body>
<div>foo <span>text </span>bar</div>
<div>foo1 <span>text1 </span>bar1</div>
</body>
</html>
becomes
<html>
<body>
<div>foo text bar</div>
<div>foo1 text1 bar1</div>
</body>
</html>
Thx
You can change the outerHTML of <span> to its innerHTML
var elms = document.querySelectorAll('div *');
elms.forEach(e => e.outerHTML = ` ${e.innerHTML} `)
//just to test the effect.
document.querySelectorAll('div').forEach(x => console.log(x.outerHTML))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>foo<span>text</span>bar</div>
<div>foo1<span>text1</span>bar1</div>
Use replace:
let div = document.getElementById("myDiv");
div.innerHTML = div.innerHTML.replace("<span>", " ").replace("</span>", " ");
span {
color: red;
}
<div id="myDiv">foo<span>text</span>bar</div>
You can do like this
$(document).ready(function(){
$("div").each(function(index,item){
$(item).html($(item).html().replace(/<\/?span[^>]*>/g,""));
})
})
$(document).ready(function(){
$("div").each(function(index,item){
$(item).html($(item).html().replace(/<\/?span[^>]*>/g,""));
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>foo <span>text</span> bar</div>
<div>foo1 <span>text1</span> bar1</div>
Simplest way would be to change innerHtml to innerText (if you want to get rid of all inner tags):
var divs = document.querySelectorAll('div');
for (i = 0; i < divs.length; i++) {
divs[i].innerHTML = divs[i].innerText;
}
span {color:red;}
<div>foo <span>text </span>bar</div>
<div>foo1 <span>text1 </span>bar1</div>

I want to change text with a button

I want to provide all my posts on my blog in 2 languages. I found a way to change the text into another language with buttons. But I can't put any images or other css styles in the text that changes. Then the buttons don't work anymore.
<button onclick="document.getElementById('chgtext').innerHTML='This is the default text. I can't put any css or html in here';">English</button>   <button onclick="document.getElementById('chgtext').innerHTML='Text changed into Another language';">Other language</button>
<div id="chgtext">This is the default text. I can't put any css or html in here</div>
Is there a way I can make something like this but with a code where I'm able to put images, font styles,... in the code?.
Or is there maybe a way to only change the text. And leave the images with multiple divs?
TEXT (changes)
IMAGE
TEXT (changes)
http://oihanevalbuenaredondo.be/2017/01/17/current-favorites-voorbeeld/ --> this is an example of a post i want in 2 languages. I need multiple images, al the text in the post needs to be changed from one language to another, with buttons
You need to iterate over all the children of your element. Using JQuery, and assuming just one level of descendants, you could use something like this...
$('#chgtxt').children().each( function() {
var oldtext = $(this).text();
if (oldtext) {
var newtext = oldtext+" CHANGED. ";
$(this).text(newtext);
}
});
You can create your own using this simple code, it simply gets an entry and replace it by it's value in the array. Ex :
var lang = {
"helloWorld": {
en: "Hello World",
fr: "Bonjour monde"
},
"mynameis": {
en: "My name is",
fr: "Mon nom est"
}
}
$(document).ready(function(){
$(body).find('.trn').each(function($elem){
var currentLang = 'en';
$($elem).html(lang[$($elem).data('trn')][currentLang]);
});
});
For each text your need to add a data with the key and a class trn, just like this.
<span class="trn" data-trn="mynameis"></span> Nicolas
Check this link for more informations
hopes it helps !
Nic
You have a single quote in the text of the first onclick "can't" which is causing the javascript to think that it is the end of the string.
You need to add a backslash "can\'t"
<button onclick="document.getElementById('chgtext').innerHTML='<p>Blue</p>This is the default text. I can\'t put any css or html in here';">English</button>  <button onclick="document.getElementById('chgtext').innerHTML='<p>Blue</p>Text changed into Another language';">Other language</button>
<div id="chgtext"><p>Blue</p>This is the default text. I can't put any css or html in here</div>
<style>
p {color:blue;}
</style>
You need to escape all quotes inside of inserted content. Have a look at snippet and try to click on buttons
<button onclick="document.getElementById('chgtext').innerHTML='This is the default text. <img src=\'http://lorempixel.com/output/nightlife-q-c-50-50-6.jpg\'> NOW I can put any css or <span style=\'color :red;\'>html</span> in here';">English</button>  
<button onclick="document.getElementById('chgtext').innerHTML='Text changed into Another <span style=\'color :red;\'>language</span>';">Other language</button>
<div id="chgtext">This is the default text. I can't put any css or html in here</div>
<p>
<style>
#eng_lang {
display: block;
}
#nl_lang {
display: none;
}
</style>
<button onclick=" document.getElementById('eng_lang').style.display='block'; document.getElementById('nl_lang').style.display='none'">English</button>   <button onclick="document.getElementById('eng_lang').style.display='none';document.getElementById('nl_lang').style.display='block'">Nederlands</button></p>
<div id="eng_lang">
<h2>Here is some text
<span style="color: green;">english</span>
</h2>
<img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRo2yKPonCY-BZrk9s69oH_-gal_yxDRgHxdyXhqP79D0YESVuB" width="120px" height="120px">
Now you can place here any text, tags and images.
</div>
<div id="nl_lang">
<h2>Here is another text
<span style="color: blue;">Netherlands</span>
</h2>
<img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQcE1c0chXugmq_V5qwp51ffAuP7ecGMsWmshnntwAXVGUgVptH" width="100px" height="100px">
Put here whatever you want.
<p>This is paragraph</p>
</div>

document.getElementById("xxx").style [duplicate]

This question already has answers here:
How to apply CSS style to all elements with same ID using one button?
(6 answers)
Closed 6 years ago.
I want to use getElementById("xxx").style.color = "xxx".
With this I want to change some css value. But the problem is when i use this and test all same id with this but it does't effect all id and effects only the first one.
Sample code is as follow:
<html>
<body>
<div id = "test">Test</div>
<div id = "test">Test</div>
<div id = "test">Test</div>
<div id = "test">Test</div>
<script>
document.getElementById("test").style.color = "blue"
</script>
</body>
</html>
What should i do to change all 4 Test to color blue.
AnyIdea pls.
Thanks
An ID must be unique in an HTML document. Write valid HTML.
To represent multiple, related elements: use a class.
You can then use getElementsByClassName or querySelectorAll to get an array-like object which you can use a for loop to access each element in turn.
var elements = document.querySelectorAll(".test");
for (var i = 0; i < elements.length; i++) {
elements[i].style.color = "blue";
}
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
Alternatively, write a stylesheet with a descendant combinator and toggle the classes on a containing element.
document.getElementById("container").classList.add("foo");
.test { color: black; }
.foo .test { color: blue; }
<div id="container">
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
</div>
As stated before, an ID must be unique. If you want to give multiple DOM-elements the same style just use 'class'.
you could try this:
<html>
<body>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<script>
var divList = document.getElementsByClassName("test");
for (var i = 0; i < divList.length; i++) {
divList[i].style.color = "red";
}
</script>
</body>
</html>
to change the style using javascript.
There are two problems with your code :
id must be unique, so you should use eg. class instead
you should loop across the different elements that are selected
This is my prefered way to correct those two problems :
<html>
<body>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<script>
Array.prototype.slice.call(
document.getElementsByClassName("test")
).forEach(function(element) {
element.style.color = "blue"
});
</script>
</body>
</html>
See also this Fiddle.
For jQuery Solution
You cannot use same id for performing same operation on all the elements
You can use class name and add style using jquery like
$(".className").css("color","blue");

Document.write alternatives examples

I have been using document.write to generate the HTML part of my page, populating it using a loop. For example I need to create 10 of the following things on my page:
<div class=" normal" id="1"
style="text-align:left;
top: 13px;
left: 5px;
height: 10em;
width: 12em;">
<div class = "wrap">
<div class = "show">
<strong>New York City
<p>Status: Cold</p>
</strong>
</div>
<div class = "noshow">
<P>0001: Normal</P>
</div>
<div class = "here">
<P>0001: online</P>
<P>0002: online</P>
</div>
</div>
</div>
I been doing :
<script>
document.write("<div class=\"");
.. you get the idea</script>
What is another way to do this with jquery or just not-document.write? Could you also provide short example applied onto the code I have above.
Jquery .html() Could be good for this purpose.
<script>
$(function() {
var htmlString = "<div>.. you get the idea</div>";
$("body").html(htmlString);
});
</script>
or this will append html:
.append()
<script>
$(function() {
var htmlString = "<div>.. you get the idea</div>";
$("body").append($(htmlString));
});
</script>
Put the entire thing in a variable :
say : var html_content = "<div class=.....";
and in your loop you can simply use .append(html_content);
You could use DOM manipulation to directly query and add node elements to the DOM.
http://www.howtocreate.co.uk/tutorials/javascript/dombasics

Categories