Replace a style value in javascript - javascript

I am looking to change a value in a tag with js.
<div class="class1" style="background-image:url(https://www.awebsite.com/sites/default/files/a_image.jpg?t=1529620960)"></div>
I want to change this :
https://www.awebsite.com/sites/default/files/a_image.jpg?t=1529620960`
to this:
https://hello.com/an-other-image.jpg
Thanks !

You can use document.querySelector to get a reference to the <div> element and then update it's style attributes.
// querySelector can use CSS selectors to find the element in the document
// note: this is assuming there is only 1 element on page with this class
var myDiv = document.querySelector('.class1');
// Style properties generally match CSS but camel cased
myDiv.style.backgroundImage = 'url("https://hello.com/an-other-image.jpg")';
You may want to consider adding an id in which case you can use an ID selector or document.getElementById.
If there are multiple elements you want to update, you can use document.querySelectorAll which will return an array of matches which you can loop over and change.
function changeToAnotherBgImage(element) {
element.style.backgroundImage = 'url("https://hello.com/an-other-image.jpg")';
}
// Plenty of alternate ways of writing, arrow function may be appropriate
document.querySelectorAll('.class1').forEach(changeToAnotherBgImage);

You can do something like:
c = document.getElementsByClassName('class1');
for(i = 0; i < c.length; i++){
c[i].style.backgroundImage = 'url(https://hello.com/an-other-image.jpg)';
}

You can do that:
const eleDiv =document.querySelector('.class').style.background = "url('your imge') no-repeat";

Related

getElementsByClassName isn't returning all elements

I'm creating a button that I should highlight certain words within a specified class, but I am having issues with it returning all elements within the class. It will only work if I specify an index, so I'm assuming there may be something wrong with the existing "for loop". Any help is appreciated!
This will work, but only "highlights" the first element in the class, of course:
var bodyText = document.getElementsByClassName('test')[0].innerHTML;
for (var i = 0; i < searchArray.length; i++) {
bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag,
highlightEndTag);}
document.getElementsByClassName('test')[0].innerHTML = bodyText;
return true;
This will not work at all:
var bodyText = document.getElementsByClassName('test').innerHTML;
for (var i = 0; i < searchArray.length; i++) {
bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag,
highlightEndTag);}
document.getElementsByClassName('test').innerHTML = bodyText;
return true;
If you want to replace multiple words in multiple elements, you need two loops:
const testElements = document.getElementsByClassName('test');
for (const element of testElements) {
for (const search of searchArray) {
element.innerHTML = doHighlight(element.innerHTML, search, highlightStartTag, highlightEndTag);
}
}
As you can see getElementsByClassName is pluralized (Elements). Indeed a same class can be assigned to multiple HTML elements. You won't find any way to ommit the [0] and you shouldn't anyway as it might mean you're getting data from the wrong node. If you need data from a specific element that you can ensure is unique then you need to give it an id and use getElementById instead.
You cannot access innerHTML in something which returns an htmlcollection
document.getElementsByClassName('test').innerHTML
Because it's written in plain english: getElementsByClassName. plural.
"Elements".
with an "s" at the end...
meaning it's a (sort of) Array (an htmlcollection)

JS: I can't get the inner HTML of elements with a specific class name

I'm trying to create a calculator out of javascript to work on my skills. I've added the class num to all of my buttons that have a number.
I'm trying to display to display the innerHTML of those buttons in the console when I click them with this code:
var num = document.getElementsByClassName('num');
num.addEventListener('click', getNum);
function getNum(){
console.log(num.innerHTML);
}
getNum();
However all I get is
num.addEventListener is not a function.
Here is my codepen: https://codepen.io/teenicarus/pen/wrEzwd
what could I be doing wrong?
You need to change the code like below. getElementsByClassName returns collection of elements. Loop through the elements and add click event listener. In getNum, you can use this to get access to the button clicked.
var num = document.getElementsByClassName('num');
for (var i = 0; i < num.length; i++) {
num[i].addEventListener('click', getNum);
}
function getNum(){
console.log(this.innerHTML);
}
You can also use Array forEach like the following:
[].forEach.call(num, function(el){
el.addEventListener('click', getNum);
})
getElementsByClassName returns a collection of elements, not a single element. If you want to get single element assign it an id attribute and use getElementById. This way you can use addEventListener function
Here's a solution you can plug directly in your codepen:
var nums = document.getElementsByClassName('num');
[].forEach.call(nums, num => num.addEventListener('click', numClick));
function numClick(){
// adding + turns the text into an actual number
console.log(+this.innerHTML);
}
getElementsByClassName() returns an HTMLCollection, to iterate over it you can pass it to [].forEach.call() like I showed above.
I also renamed the handler to numClick, since it doesn't "get" the number. And added +, which is a nice shortcut to turn text into a number (otherwise, adding two numbers would yield unexpected results, like "1" + "2" => "12"
The .getElementsByClassName returns not an element, but a collection of them.
You can access elements using .getElementsByClassName(num)[element's sequential number], or better use id's and getElementById method.
Here is the modified code for your desired output.just copy and try:
var num = document.getElementsByClassName('num');
//num.addEventListener('click', getNum);
for (var i = 0; i < num.length; i++) {
num[i].addEventListener('click', getNum);
}
function getNum(){
document.getElementById('result').innerHTML+=this.innerHTML;
console.log('value:'+this.innerHTML);
}
//getNum();
As you tagged Jquery to your question I suppose that you are able to use Jquery as well. You can grab the clicked element's class and referance it with 'this' to get its text.
$('.num').click(function(){
var x = $(this).text();
console.log(x);
});
This is a working example you can check the console.log DEMO

GetElementByID - Multiple IDs

doStuff(document.getElementById("myCircle1" "myCircle2" "myCircle3" "myCircle4"));
This doesn't work, so do I need a comma or semi-colon to make this work?
document.getElementById() only supports one name at a time and only returns a single node not an array of nodes. You have several different options:
You could implement your own function that takes multiple ids and returns multiple elements.
You could use document.querySelectorAll() that allows you to specify multiple ids in a CSS selector string .
You could put a common class names on all those nodes and use document.getElementsByClassName() with a single class name.
Examples of each option:
doStuff(document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4"));
or:
// put a common class on each object
doStuff(document.getElementsByClassName("circles"));
or:
function getElementsById(ids) {
var idList = ids.split(" ");
var results = [], item;
for (var i = 0; i < idList.length; i++) {
item = document.getElementById(idList[i]);
if (item) {
results.push(item);
}
}
return(results);
}
doStuff(getElementsById("myCircle1 myCircle2 myCircle3 myCircle4"));
This will not work, getElementById will query only one element by time.
You can use document.querySelectorAll("#myCircle1, #myCircle2") for querying more then one element.
ES6 or newer
With the new version of the JavaScript, you can also convert the results into an array to easily transverse it.
Example:
const elementsList = document.querySelectorAll("#myCircle1, #myCircle2");
const elementsArray = [...elementsList];
// Now you can use cool array prototypes
elementsArray.forEach(element => {
console.log(element);
});
How to query a list of IDs in ES6
Another easy way if you have an array of IDs is to use the language to build your query, example:
const ids = ['myCircle1', 'myCircle2', 'myCircle3'];
const elements = document.querySelectorAll(ids.map(id => `#${id}`).join(', '));
No, it won't work.
document.getElementById() method accepts only one argument.
However, you may always set classes to the elements and use getElementsByClassName() instead. Another option for modern browsers is to use querySelectorAll() method:
document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4");
I suggest using ES5 array methods:
["myCircle1","myCircle2","myCircle3","myCircle4"] // Array of IDs
.map(document.getElementById, document) // Array of elements
.forEach(doStuff);
Then doStuff will be called once for each element, and will receive 3 arguments: the element, the index of the element inside the array of elements, and the array of elements.
getElementByID is exactly that - get an element by id.
Maybe you want to give those elements a circle class and getElementsByClassName
document.getElementById() only takes one argument. You can give them a class name and use getElementsByClassName() .
Dunno if something like this works in js, in PHP and Python which i use quite often it is possible.
Maybe just use for loop like:
function doStuff(){
for(i=1; i<=4; i++){
var i = document.getElementById("myCiricle"+i);
}
}
Vulgo has the right idea on this thread. I believe his solution is the easiest of the bunch, although his answer could have been a little more in-depth. Here is something that worked for me. I have provided an example.
<h1 id="hello1">Hello World</h1>
<h2 id="hello2">Random</h2>
<button id="click">Click To Hide</button>
<script>
document.getElementById('click').addEventListener('click', function(){
doStuff();
});
function doStuff() {
for(var i=1; i<=2; i++){
var el = document.getElementById("hello" + i);
el.style.display = 'none';
}
}
</script>
Obviously just change the integers in the for loop to account for however many elements you are targeting, which in this example was 2.
The best way to do it, is to define a function, and pass it a parameter of the ID's name that you want to grab from the DOM, then every time you want to grab an ID and store it inside an array, then you can call the function
<p id="testing">Demo test!</p>
function grabbingId(element){
var storeId = document.getElementById(element);
return storeId;
}
grabbingId("testing").syle.color = "red";
You can use something like this whit array and for loop.
<p id='fisrt'>??????</p>
<p id='second'>??????</p>
<p id='third'>??????</p>
<p id='forth'>??????</p>
<p id='fifth'>??????</p>
<button id="change" onclick="changeColor()">color red</button>
<script>
var ids = ['fisrt','second','third','forth','fifth'];
function changeColor() {
for (var i = 0; i < ids.length; i++) {
document.getElementById(ids[i]).style.color='red';
}
}
</script>
For me worked flawles something like this
doStuff(
document.getElementById("myCircle1") ,
document.getElementById("myCircle2") ,
document.getElementById("myCircle3") ,
document.getElementById("myCircle4")
);
Use jQuery or similar to get access to the collection of elements in only one sentence. Of course, you need to put something like this in your html's "head" section:
<script type='text/javascript' src='url/to/my/jquery.1.xx.yy.js' ...>
So here is the magic:
.- First of all let's supose that you have some divs with IDs as you wrote, i.e.,
...some html...
<div id='MyCircle1'>some_inner_html_tags</div>
...more html...
<div id='MyCircle2'>more_html_tags_here</div>
...blabla...
<div id='MyCircleN'>more_and_more_tags_again</div>
...zzz...
.- With this 'spell' jQuery will return a collection of objects representing all div elements with IDs containing the entire string "myCircle" anywhere:
$("div[id*='myCircle']")
This is all! Note that you get rid of details like the numeric suffix, that you can manipulate all the divs in a single sentence, animate them... Voilá!
$("div[id*='myCircle']").addClass("myCircleDivClass").hide().fadeIn(1000);
Prove this in your browser's script console (press F12) right now!
As stated by jfriend00,
document.getElementById() only supports one name at a time and only returns a single node not an array of nodes.
However, here's some example code I created which you can give one or a comma separated list of id's. It will give you one or many elements in an array. If there are any errors, it will return an array with an Error as the only entry.
function safelyGetElementsByIds(ids){
if(typeof ids !== 'string') return new Error('ids must be a comma seperated string of ids or a single id string');
ids = ids.split(",");
let elements = [];
for(let i=0, len = ids.length; i<len; i++){
const currId = ids[i];
const currElement = (document.getElementById(currId) || new Error(currId + ' is not an HTML Element'));
if(currElement instanceof Error) return [currElement];
elements.push(currElement);
};
return elements;
}
safelyGetElementsByIds('realId1'); //returns [<HTML Element>]
safelyGetElementsByIds('fakeId1'); //returns [Error : fakeId1 is not an HTML Element]
safelyGetElementsByIds('realId1', 'realId2', 'realId3'); //returns [<HTML Element>,<HTML Element>,<HTML Element>]
safelyGetElementsByIds('realId1', 'realId2', 'fakeId3'); //returns [Error : fakeId3 is not an HTML Element]
If, like me, you want to create an or-like construction, where either of the elements is available on the page, you could use querySelector. querySelector tries locating the first id in the list, and if it can't be found continues to the next until it finds an element.
The difference with querySelectorAll is that it only finds a single element, so looping is not necessary.
document.querySelector('#myCircle1, #myCircle2, #myCircle3, #myCircle4');
here is the solution
if (
document.getElementById('73536573').value != '' &&
document.getElementById('1081743273').value != '' &&
document.getElementById('357118391').value != '' &&
document.getElementById('1238321094').value != '' &&
document.getElementById('1118122010').value != ''
) {
code
}
You can do it with document.getElementByID Here is how.
function dostuff (var here) {
if(add statment here) {
document.getElementById('First ID'));
document.getElementById('Second ID'));
}
}
There you go! xD

access divs of same class name using javascript

I have the following html code-
<div class="search_results">...</div>
<div class="search_results">...</div>
<div class="search_results">...</div>
The divs are automatically generated by a javasciprt function. Is there a way to access only the first div/or a specific div of the same class name "search_results" with javascript?
If you use JQuery $(".search_results").first(). Else you need to use document.getElementsByClassName("search_results")[0];
You can use getElementsByClassName which returns a NodeList (which is an array-like object). You can then access individual elements of that using normal array syntax. This example will return the first element:
var firstDiv = document.getElementsByClassName("search_results")[0];
Or, you could use querySelector, which returns the first element found:
var firstDiv = document.querySelector(".search_results");
If you want to return all matched elements, you can use querySelectorAll, which returns a NodeList, like getElementsByClassName.
Use getElementsByClassName or querySelector (if available):
function findElementsByTagNameAndClassName(tag, class_name) {
if(typeof document.querySelector !== 'undefined') {
return document.querySelector(tag + ' .' + class_name);
}
var els = document.getElementsByClassName(class_name);
var result = [];
for(var i = 0; i < els.length; ++i) {
if(els[i].nodeName === tag) {
result.push(els[i]);
}
}
return result;
}
var firstDiv = findElementsByTagNameAndClassName('div', 'search_results')[0];
If you're using JQuery:
$("div.search_results").first() for later versions of JQuery and $("div.search_results")[0] for older ones.
No Jquery:
document.getElementsByClassName
If you want to access a specific instance, you will want to add an id attribute to the elements, for example:
<div class="search_results" id="result_1">...</div>
<div class="search_results" id="result_2">...</div>
<div class="search_results" id="result_3">...</div>
If that's not an option, you can access the n'th item with the classname (starting from 0) using
var divN = document.getElementsByClassName("search_results")[n];

Getting element by a custom attribute using JavaScript

I have an XHTML page where each HTML element has a unique custom attribute, like this:
<div class="logo" tokenid="14"></div>
I need a way to find this element by ID, similar to document.getElementById(), but instead of using a general ID, I want to search for the element using my custom "tokenid" attribute. Something like this:
document.getElementByTokenId('14');
Is that possible? If yes - any hint would be greatly appreciated.
Thanks.
It is not good to use custom attributes in the HTML. If any, you should use HTML5's data attributes.
Nevertheless you can write your own function that traverses the tree, but that will be quite slow compared to getElementById because you cannot make use of any index:
function getElementByAttribute(attr, value, root) {
root = root || document.body;
if(root.hasAttribute(attr) && root.getAttribute(attr) == value) {
return root;
}
var children = root.children,
element;
for(var i = children.length; i--; ) {
element = getElementByAttribute(attr, value, children[i]);
if(element) {
return element;
}
}
return null;
}
In the worst case, this will traverse the whole tree. Think about how to change your concept so that you can make use browser functions as much as possible.
In newer browsers you use of the querySelector method, where it would just be:
var element = document.querySelector('[tokenid="14"]');
This will be much faster too.
Update: Please note #Andy E's comment below. It might be that you run into problems with IE (as always ;)). If you do a lot of element retrieval of this kind, you really should consider using a JavaScript library such as jQuery, as the others mentioned. It hides all these browser differences.
<div data-automation="something">
</div>
document.querySelector("div[data-automation]")
=> finds the div
document.querySelector("div[data-automation='something']")
=> finds the div with a value
If you're using jQuery, you can use some of their selector magic to do something like this:
$('div[tokenid=14]')
as your selector.
You can accomplish this with JQuery:
$('[tokenid=14]')
Here's a fiddle for an example.
If you're willing to use JQuery, then:
var myElement = $('div[tokenid="14"]').get();
Doing this with vanilla JavaScript will do the trick:
const something = document.querySelectorAll('[data-something]')
Use this more stable Function:
function getElementsByAttribute(attr, value) {
var match = [];
/* Get the droids we are looking for*/
var elements = document.getElementsByTagName("*");
/* Loop through all elements */
for (var ii = 0, ln = elements.length; ii < ln; ii++) {
if (elements[ii].nodeType === 1){
if (elements[ii].name != null){
/* If a value was passed, make sure it matches the elements */
if (value) {
if (elements[ii].getAttribute(attr) === value)
match.push(elements[ii]);
} else {
/* Else, simply push it */
match.push(elements[ii]);
}
}
}
}
return match;
};

Categories

Resources