Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am needing to add what looks like an attribute into a div but I am not able to use the attribute tag because it has invalid characters. I can target the div by using
var ele = document.getElementById('divid');
But I then need to insert into the div tag a variable like this:
var topic = 'topic-Close=SCENARIO_COPIER_POPUP_CLOSE '
So I am wanting the div to look like
<div id="divid" topic-Close=SCENARIO_COPIER_POPUP_CLOSE> CONTENT OF DIV </div>
I am unable to use ele.setAttribute because of the invalid characters in the variable. Is there another way to add something to the DOM of a div dynamically that has invalid characters for an attribute tag?
You've said you can't, but you can add the attribute defined in that string via setAttribute:
var ele = document.getElementById('divid');
var topic = 'topic-Close=SCENARIO_COPIER_POPUP_CLOSE ';
const [name, value] = topic.split("=", 2);
ele.setAttribute(name, value);
console.log(ele.outerHTML);
<div id="divid"></div>
Note that:
It's an invalid attribute. The spec doesn't define it, and custom attributes must start with data-.
Attribute names are not case-sensitive in HTML, so the browser may normalize it (for instance, Chrome shows it in lower case).
Use data-attrName format for attribute name
ele.setAttribute("data-topic-Close", "SCENARIO_COPIER_POPUP_CLOSE")
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 months ago.
Improve this question
I am using $html attrib for inserting data attrib to my index.html file using jquery. I have also typed attribs manually.
Now is it possible if I press f12 to see the $html attribs first before the manual attribs?
E.g
html data-id="Code" lang="en-PH"
i set lang attrib manually and data id code via jquery.
If I press f12 lang comes first before data id. I want data id first before lang.
Is it possible?
It's possible, by iterating over all attributes that exist on the element and deleting them, then adding your own new attribute, then re-adding the originals...
const div = $('div')[0];
// Cache and remove existing attributes
const attribs = [];
for (const attrib of div.attributes) {
attribs.push([attrib.name, attrib.value]);
div.removeAttribute(attrib.name);
}
// Add your own
$(div).attr('dynamicAttrib', 'dynamicVal');
// Re-add original attibutes
for (const [name, value] of attribs) {
$(div).attr(name, value);
}
console.log(div.outerHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div firstAttrib="firstValue"></div>
But whether a piece of code works or not should not depend on attribute order. It's somewhat convoluted and doesn't accomplish anything, and could even cause problems; I'd recommend not bothering.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hello there am trying to make an image gallery for example lets say that I have multiple images and I want to change their opacity when I hover over them by using JavaScript I know that this is possible with CSS but am trying to accomplish this with JavaScript I tried using get Elements By Tag Name method but the problem it just can access one element by time so can I do that thanks
Try this:
var elements = document.getElementsByTagName("img");
Array.prototype.forEach.call(elements, function (e) {
// Here you can access each image individually as 'e'.
});
When you hover, get the ID of that image. Then loop through all images (example above) and set their opacity. If the element is equal to the one you clicked on (remember, you just took the ID so you can use it), just skip to the next one using continue;.
you have to collect you image elements like
var images = document.getElementsByTagName("img");
then you have to do like
Array.prototype.forEach.call(images, e => e.addEventListener("mouseover", function( event ) { do something}));
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm a javascript newbie so go easy on me. I'm wanting to select a bunch of text that is identifiable only by inline CSS (not classes or ids or anything), and create a toggle that turns it on and off. So -- find everything with backgroundColor = '#eed6b4' and toggle display='none' / 'inline-block'
Needing the javascript and html... thx
=====================
This is what I tried originally:
<script type="text/javascript">
function toggleVisibility() {
var codeNum = document.getElementsByClassName('syntaxHighlightingPlugin');
i = codeNum.length;
while(i--) {
codeNum[1].style.backgroundColor = '#eed6b4';
if(codeNum.style.display == 'inline-block')
codeNum.style.display = 'none';
else
codeNum.style.display = 'inline-block';
}
}
</script>
<button type="button" onclick="toggleVisibility();"> Hide numbers (for copying) </button>
Oh, and as I replied to a comment, the twist on this is that it's for text rendered by a TWiki plugin, so I have no control over the resulting CSS --- which, as I said, has no classes --- also, since it's rendered, I think I may need to use something like getComputedStyle (?).
It's generally bad practice to use inline css, and to make your Javascript dependant on that inline CSS is also not a good idea. However, if you wanted to select an element based on the value of an attribute, you can use the attribute value selector like this:
$("[style='backgroundColor *= #eed6b4']").hide();
Reminder: This uses jQuery.
You could set a class to that background color and then filter by class name $(".classname").
OR
You could add a new selector like explained here:
Is there a style selector in jQuery?
Not necessarily a great idea, but you could add a new Sizzle selector for it:
$.expr[':'].width = function(elem, pos, match) {
return $(elem).width() == parseInt(match[3]);
}
which you could then use like so:
$('div:width(970)')
//That's going to be horrifically slow, though, so you'd want to narrow down on the number >of elements you're comparing with something like :
$('#navbar>div:width(970)')
//to only select those divs that are direct descendants of the navbar, which also have a >width of 970px.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Suppose the following markup:
<body>
link [ some text here
link [ some more text here
</body>
Is there anyway to use jQuery to remove the ' [ ' from the top line but not the bottom one?
Note: I don't have the access to the markup, but I can add elements, divs etc. using jQuery if I wanted to. BUT jQuery does not need to target the string of ' ] ' in particular - it can be something like "remove next 3 characters after uniqueLink1.
jQuery doesn't really help much with manipulating text nodes, but here it is:
var tn = $('a[name="uniqueLink1"]')[0].nextSibling;
tn.nodeValue = tn.nodeValue.replace('[', '');
Demo
$()[n] is a shorthand for $().get(n), so [0] will return a reference to the first matched DOM element inside the jQuery object, the uniqueLink1 anchor.
nextSibling, as the name implies, grabs the next sibling node. In this case, the text node that follows the given anchor element.
nodeValue gets and sets the content of the text node.
String.replace() given a string as the first argument replaces only the first occurrence, thus this should be enough enough given the DOM structure is similar to the posted one.
This will filter the textnodes, and remove a [ from the first on it finds:
var textNode = $('body').contents().filter(function() {
return this.nodeType == 3;
}).eq(1);
textNode.replaceWith(document.createTextNode(textNode[0].textContent.replace('[','')));
Example fiddle
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can i get the image of the <img> tag and store it in a variable in javascript (or equivalently jquery) ?
(actually i want to swap the images between two <img> tags).
jQuery has specific uses for .prop() vs .attr() so make sure to read up on that:
http://api.jquery.com/attr/
But once you assigned the src of one image to a variable:
var img1_src = $("img#image1").attr("src");
You can then take that variable and shove it into the source of another image:
$('img#img2').attr('src', img1_src);
you could assign id for the image , and do:
var img_src = document.getElementById("your_image_id").src;
or with jQuery
var img_src = $("img#your_image_id").prop("src");
Use attr() or prop() to get the src of an image tag.
Like this
$('#imageId').attr('src');
Check .attr() and .prop()
var src = document.getElementsByTagName('img')[0].src;
Regards
Use Jquery attr attribute to get the src attribute of your image
<img src="#" class="my_img"></img>
var img = $('.my_img').attr('src');
Note styles applied through id attribute are not applicable to img tags
I would do that with JavaScript preferably using the two images IDs.
var img1_src = document.getElementById("img1_id").src;
document.getElementById("img2_id").src = img1_src;