How to use setAttribute in javascript - javascript

Is this the correct format?
var title = new_element.setAttribute('jcarouselindex', "'items+1'");
alert(title);

No need to put the second parameter in quotes.
var title = new_element.setAttribute('jcarouselindex', items+1);
If you want to set a custom attribute then you can use HTML5 data-attributes, something like
var title = new_element.setAttribute('data-jcarouselindex', items+1);

It is syntactically correct JS/DOM, but there is no 'jcarouselindex' attribute in HTML and using setAttribute (as opposed to setting properties that map to attributes) is generally bad practice as it is buggy in MSIE (although not in such a way that will cause a problem in this case).
You might not be intending to have <foo jcarouselindex="'items+1'"> as your end result though.

Using jQuery?
var title = $('#new_element').attr('jcarouselindex', "'items+1'");
alert(title);

You have too many quotes:
var index = items + 1;
new_element.setAttribute('jcarouselindex', index);
Remark: there's no jcarouselindex attribute defined in HTML elements so this is not very clean code.

Related

How can I set attribute which ends with dollar sign using Javascript?

I'm trying to create a pre-processor that converts some custom markup in a file into attribute names which works with Polymer's data binding $= annotation, however I've come across a stumbling block.
I cannot set attributes using Javascript that contain a dollar sign.
I'm trying to convert
<p stuff="align bottom#md top#lg; offset 2gu#md; "></p>
to
<p align-bottom$="{{globals.abovemd}}" align-top$="{{globals.abovelg}}" offset-2gu$="{{globals.abovemd}}">
I have tried:
.setAttribute("align-bottom$", "{{globals.abovemd}}");
But it won't work because the attribute name cannot contain a dollar sign.
Can any one think of a way I can get around this?
This might do the trick(setting invalid attribute names), although obviously not valid in all cases:
function setDollar(el,name,val){
var attrs = [];
var tagName = el.tagName;
for (var i = 0; i < el.attributes.length; i++) {
var attrib = el.attributes[i];
if (attrib.specified) attrs.push(attrib.name+'="'+attrib.value+'"')
}
el.outerHTML = '<'+tagName+ ' '+name+'$="'+val+'"'+attrs.join(' ')+'>'+ el.innerHTML+'</'+el.tagName+'>';
attrs.forEach((attr)=>el.setAttribute(attr.name, attr.value))
}
setDollar(document.querySelector('#wow'),'foo','bar')
<div id="wow"><p>something</p></div>
Still, needs checking for closing tag etc.
Just exclude the $ anytime you are dealing with that property. The $ is just reflecting the property to the attribute onto that DOM element.
.setAttribute("align-bottom", globals.abovemd);
Pretty sure this gonna work
(you need put align-bottom$="" into your html first, this is just to update the value):
.attributes['align-bottom$'].value = "{{globals.abovemd}}";

How to fill this textbox? [duplicate]

I need to set the text within a DIV element dynamically. What is the best, browser safe approach? I have prototypejs and scriptaculous available.
<div id="panel">
<div id="field_name">TEXT GOES HERE</div>
</div>
Here's what the function will look like:
function showPanel(fieldName) {
var fieldNameElement = document.getElementById('field_name');
//Make replacement here
}
You can simply use:
fieldNameElement.innerHTML = "My new text!";
Updated for everyone reading this in 2013 and later:
This answer has a lot of SEO, but all the answers are severely out of date and depend on libraries to do things that all current browsers do out of the box.
To replace text inside a div element, use Node.textContent, which is provided in all current browsers.
fieldNameElement.textContent = "New text";
function showPanel(fieldName) {
var fieldNameElement = document.getElementById("field_name");
while(fieldNameElement.childNodes.length >= 1) {
fieldNameElement.removeChild(fieldNameElement.firstChild);
}
fieldNameElement.appendChild(fieldNameElement.ownerDocument.createTextNode(fieldName));
}
The advantages of doing it this way:
It only uses the DOM, so the technique is portable to other languages, and doesn't rely on the non-standard innerHTML
fieldName might contain HTML, which could be an attempted XSS attack. If we know it's just text, we should be creating a text node, instead of having the browser parse it for HTML
If I were going to use a javascript library, I'd use jQuery, and do this:
$("div#field_name").text(fieldName);
Note that #AnthonyWJones' comment is correct: "field_name" isn't a particularly descriptive id or variable name.
I would use Prototype's update method which supports plain text, an HTML snippet or any JavaScript object that defines a toString method.
$("field_name").update("New text");
Element.update documentation
$('field_name').innerHTML = 'Your text.';
One of the nifty features of Prototype is that $('field_name') does the same thing as document.getElementById('field_name'). Use it! :-)
John Topley's answer using Prototype's update function is another good solution.
The quick answer is to use innerHTML (or prototype's update method which pretty much the same thing). The problem with innerHTML is you need to escape the content being assigned. Depending on your targets you will need to do that with other code OR
in IE:-
document.getElementById("field_name").innerText = newText;
in FF:-
document.getElementById("field_name").textContent = newText;
(Actually of FF have the following present in by code)
HTMLElement.prototype.__defineGetter__("innerText", function () { return this.textContent; })
HTMLElement.prototype.__defineSetter__("innerText", function (inputText) { this.textContent = inputText; })
Now I can just use innerText if you need widest possible browser support then this is not a complete solution but neither is using innerHTML in the raw.
If you really want us to just continue where you left off, you could do:
if (fieldNameElement)
fieldNameElement.innerHTML = 'some HTML';
nodeValue is also a standard DOM property you can use:
function showPanel(fieldName) {
var fieldNameElement = document.getElementById(field_name);
if(fieldNameElement.firstChild)
fieldNameElement.firstChild.nodeValue = "New Text";
}
el.innerHTML='';
el.appendChild(document.createTextNode("yo"));
If you're inclined to start using a lot of JavaScript on your site, jQuery makes playing with the DOM extremely simple.
http://docs.jquery.com/Manipulation
Makes it as simple as:
$("#field-name").text("Some new text.");
Use innerText if you can't assume structure
- Use Text#data to update existing text
Performance Test
function showPanel(fieldName) {
var fieldNameElement = document.getElementById(field_name);
fieldNameElement.removeChild(fieldNameElement.firstChild);
var newText = document.createTextNode("New Text");
fieldNameElement.appendChild(newText);
}
Here's an easy jQuery way:
var el = $('#yourid .yourclass');
el.html(el.html().replace(/Old Text/ig, "New Text"));
In HTML put this
<div id="field_name">TEXT GOES HERE</div>
In Javascript put this
var fieldNameElement = document.getElementById('field_name');
if (fieldNameElement)
{fieldNameElement.innerHTML = 'some HTML';}

Javascript - How to get attribute value from a tag, inside a specific div class?

Snippet of HTML code I need to retrieve values from:
<div class="elgg-foot">
<input type="hidden" value="41" name="guid">
<input class="elgg-button elgg-button-submit" type="submit" value="Save">
</div>
I need to get the value 41, which is simple enough with:
var x = document.getElementsByTagName("input")[0];
var y = x.attributes[1].value;
However I need to make sure I'm actually retrieving values from inside "elgg-foot", because there are multiple div classes in the HTML code.
I can get the class like this:
var a = document.getElementsByClassName("elgg-foot")[0];
And then I tried to combine it in various ways with var x, but I don't really know the syntax/logic to do it.
For example:
var full = a.getElementsByTagName("input")[0];
So: Retrieve value 41 from inside unique class elg-foot.
I spent hours googling for this, but couldn't find a solution (partly because I don't know exactly what to search for)
Edit: Thanks for the answers everyone, they all seem to work. I almost had it working myself, just forgot a [0] somewhere in my original code. Appreciate the JQuery as well, never used it before :-)
The easiest way is to use jQuery and use CSS selectors:
$(".elgg-foot") will indeed always get you an element with class "elgg-foot", but if you go one step further, you can use descendent selectors:
$(".elgg-foot input[name='guid']").val()
That ensures that you only get the input named guid that is a child of the element labelled with class elgg-foot.
The equivalent in modern browsers is the native querySelectorAll method:
document.querySelectorAll(".elgg-foot input[name='guid']")
or you can do what you have yourself:
var x = document.getElementsByClassName("elgg-foot")
var y = x.getElementsByTagName("input")[0];
Assuming you know it is always the first input within the div
You can combine it like this:
var a = document.getElementsByClassName("elgg-foot")[0];
var b = a.getElementsByTagName("input")[0];
var attribute = b.attributes[1].value;
console.log(attribute); // print 41
Think of the DOM as the tree that it is. You can get elements from elements in the same way you get from the root (the document).
You can use querySelector like
var x = document.querySelector(".elgg-foot input");
var y = x.value;
query the dom by selector https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
var fourty1 = document.querySelector('.elgg-foot input[name=guid]').value;
querySelector will return the first match from the selector. This selector will find the element with class elgg-foot and then look at the input element inside of that for one named guid and then take the value of the selected element.
I think the simplest way would be using JQuery. But using only javascript,
the simplest way would be:
var div = document.getElementsByClassName("elgg-foot")[0];
var input = div.getElementsByTagName("input")[0];
alert(input.value)
Take a look at this JSFiddle here: http://jsfiddle.net/2oa5evro/

Stripping text with javascript

Hi I'm a newbie with javascript and I was wondering how do I strip all the text except the word TB_iframeContent800 . the digits at the end varies.
here is an example string
<iframe frameborder="0" style="width: 670px; height: 401px;" onload="tb_showIframe()" name="TB_iframeContent80" id="TB_iframeContent" src="http://www.gorgeoushentai.com/wp-admin/media-upload.php?post_id=33&" hspace="0">This feature requires inline frames. You have iframes disabled or your browser does not support them.</iframe>
I want to extract TB_iframeContent80 and store it as a variable. So how can you do this using regex with javascript? please note the last 2 digits varies cause the number always changes so it sometimes become a 3 digit number.
var iframeName = document.getElementsByTagName("iframe")[0].name
if you've include jQuery then it could be something like this:
var iframeName = $("iframe:first").attr("name");
If jQuery is an option I think you are looking for something like this
$('iframe[name^="TB_iframeContent"]')
If you wont use DOM (because code analysis etc) just try this regex
var code = '<iframe ... /iframe>';
var result = code.match( /name="([^"]*)"/ );
var extract = result[1];
this selects the content of the name attribute
You could load html youre parsing like this and use DOM to get its name (its easier and more reliable way than using a regex):
var loadhtml = document.createElement('div');
loadhtml.innerHTML = 'yourHtml';
var theName = loadhtml.getElementsByTagName('iframe')[0].name;
If you use Jquery you could consider attr("name") as way to get name
However if you insist using a Regex here is one :
/< *iframe[^>]*name *= *['"]([^'"]*)/

Is there a way to convert HTML into normal text without actually write it to a selector with Jquery?

I understand so far that in Jquery, with html() function, we can convert HTML into text, for example,
$("#myDiv").html(result);
converts "result" (which is the html code) into normal text and display it in myDiv.
Now, my question is, is there a way I can simply convert the html and put it into a variable?
for example:
var temp;
temp = html(result);
something like this, of course this does not work, but how can I put the converted into a variable without write it to the screen? Since I'm checking the converted in a loop, thought it's quite and waste of resource if keep writing it to the screen for every single loop.
Edit:
Sorry for the confusion, for example, if result is " <p>abc</p> " then $(#mydiv).html(result) makes mydiv display "abc", which "converts" html into normal text by removing the <p> tags. So how can I put "abc" into a variable without doing something like var temp=$(#mydiv).text()?
Here is no-jQuery solution:
function htmlToText(html) {
var temp = document.createElement('div');
temp.innerHTML = html;
return temp.textContent; // Or return temp.innerText if you need to return only visible text. It's slower.
}
Works great in IE ≥9.
No, the html method doesn't turn HTML code into text, it turns HTML code into DOM elements. The browser will parse the HTML code and create elements from it.
You don't have to put the HTML code into the page to have it parsed into elements, you can do that in an independent element:
var d = $('<div>').html(result);
Now you have a jQuery object that contains a div element that has the elements from the parsed HTML code as children. Or:
var d = $(result);
Now you have a jQuery object that contains the elements from the parsed HTML code.
You could simply strip all HTML tags:
var text = html.replace(/(<([^>]+)>)/g, "");
Why not use .text()
$("#myDiv").html($(result).text());
you can try:
var tmp = $("<div>").attr("style","display:none");
var html_text = tmp.html(result).text();
tmp.remove();
But the way with modifying string with regular expression is simpler, because it doesn't use DOM traversal.
You may replace html to text string with regexp like in answer of user Crozin.
P.S.
Also you may like the way when <br> is replacing with newline-symbols:
var text = html.replace(/<\s*br[^>]?>/,'\n')
.replace(/(<([^>]+)>)/g, "");
var temp = $(your_selector).html();
the variable temp is a string containing the HTML
$("#myDiv").html(result); is not formatting text into html code. You can use .html() to do a couple of things.
if you say $("#myDiv").html(); where you are not passing in parameters to the `html()' function then you are "GETTING" the html that is currently in that div element.
so you could say,
var whatsInThisDiv = $("#myDiv").html();
console.log(whatsInThisDiv); //will print whatever is nested inside of <div id="myDiv"></div>
if you pass in a parameter with your .html() call you will be setting the html to what is stored inside the variable or string you pass. For instance
var htmlToReplaceCurrent = '<div id="childOfmyDiv">Hi! Im a child.</div>';
$("#myDiv").html(htmlToReplaceCurrent);
That will leave your dom looking like this...
<div id="myDiv">
<div id="childOfmyDiv">Hi! Im a child.</div>
</div>
Easiest, safe solution - use Dom Parser
For more advanced usage - I suggest you try Dompurify
It's cross-browser (and supports Node js). only 19kb gziped
Here is a fiddle I've created that converts HTML to text
const dirty = "Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>";
const config = { ALLOWED_TAGS: [''], KEEP_CONTENT: true, USE_PROFILES: { html: true } };
// Clean HTML string and write into the div
const clean = DOMPurify.sanitize(dirty, config);
document.getElementById('sanitized').innerText = clean;
Input: Hello <script>in script<\/script> <b>world</b><p> Many other <br/>tags are stripped</p>
Output: Hello world Many other tags are stripped
Using the dom has several disadvantages. The one not mentioned in the other answers: Media will be loaded, causing network traffic.
I recommend using a regular expression to remove the tags after replacing certain tags like br, p, ol, ul, and headers into \n newlines.

Categories