.innerHTML vs. createElement() | setAttribute() vs. Direct* - javascript

I was told this was not "proper", I did not worry about it until I started getting a run-time error in IE9. Here is the code I need converted to use object properties.
Why is innerHTML not considered best practice?
var c=document.createElement('div');
c.innerHTML= '<a name="a1" class="b" href="' + d[2].value + '">' + d[1].value + '</a>';

It's strange that you're putting an A element inside an A element but the below should work.
var c=document.createElement('a');
c.name = "a1";
c.className = "b";
c.href = d[2].value;
c.appendChild(document.createTextNode(d[1].value));
This assumes that d[1].value is not known to be well formed HTML from a trusted source so it is likely to be more robust against XSS than the innerHTML code.

innerHTML is perfectly fine, you are just not using it correctly.
innerHTML targets the content of a tag. meaning what's between <a> and </a>
you need to set your d[2].value with setAttribute and only d[1].value with innerHTML
this should be fine (untested)
var c=document.createElement('a');
c.setAttribute("href",d[2].value);
c.setAttribute("name","a1");
c.setAttribute("class","b");
c.innerHTML = d[1].value;
check these references and examples for setAttribute (method) and innerHTML (property)

It looks like you are creating an anchor - by using document.createElement('a') - and then creating another anchor within it. So, basically your HTML is going to look like this:
<a>
Click Here
</a>
This is not right. This is the reason why using innerHTML for anchors is not good. I think you should do it as follows:
c.setAttribute('class', 'signature');
c.setAttribute('href', 'xyz');
and so on.
You can also set the href and other attributes directly on the anchor using javascript. See http://www.w3schools.com/jsref/dom_obj_anchor.asp (Anchor object properties).

Related

How to dynamically add data from a span tag into a href tag

I think this may have a simple answer that I'm missing. The following tag inserts a TV show name into any page on my website:
<span class="show-title"></span>
what I'm trying to do is incorporate that data dynamically into a HREF URL link.
So, let's say on the page I'm on:
produced the result: GOTHAM.
I'd like to then use that data to create this url:
https://en.wikipedia.org/wiki/GOTHAM_(TV_series)
So I'm trying stuff like:
</span>_(TV_series)"> Link
or
Link
nothing working - any help would be awesome. Thanks!
You could do something like this:
In HTML
<a class="wikipedia-link">Link</a>
And your JavaScript function:
setLink(showTitle) {
var link = document.getElementsByClassName("wikipedia-link");
link.setAttribute("href", "https://en.wikipedia.org/wiki/" + showTitle + "_(TV_series)");
}
The html you use is wrong. span shouldn't be inside tag a. No tag inside another.
If your result is in javascript variable, you can set the url using jquery.
$('a').attr('href', "https://en.wikipedia.org/wiki/" + result + "_(TV_series)");
result variable is your desired result.
Although there's better ways of going about doing this, I'm going to answer the question in the context in which you presented it:
First, give the url link a class or ID so you can easily select it with JavaScript to change the href value later. Also, don't try to nest the span tag anywhere inside the a tag. Leave it outside.
<span class="show-title">GOTHAM</span>
Link
Next, in a JavaScript file or a <script> tag, define your variables:
var showTitle, showWikipediaLink, linkElement
Then, assign value to your newly defined variables
linkElement = document.querySelector('.show-wikipedia-link');
showTitle = document.querySelector('.show-title').innerText;
showWikipediaLink = 'https://en.wikipedia.org/wiki/' + showTitle + '_(TV_series)';
Finally, use JavaScript to update the href value of the link element to the show's Wikipedia link:
linkElement.href = showWikipediaLink;

Get an attributes value of the ALT attribute of a hyperlink

My a-tag (link) contains innerHTML which is an image like this:
.innerHTML = <img alt="hello world" src="/Content/Images/test.png">
How can I get the text of the alt attribute with JQuery?
You really don't need jQuery. If you have the a element you can do this:
// lets call the anchor tag `link`
var alt = link.getElementsByTagName('img')[0].alt; // assuming a single image tag
Remember attributes map to properties (most), and unless the property is changed, or the attribute, the two should reflect the same data (there are edge cases to this, but they can be handled case-by-case).
If you truly do need the attribute there is
var alt = link.getElementsByTagName('img')[0].getAttribute('alt');
Last scenario is if you only have the image tag as a string.
var str = '<img alt="hello world" src="/Content/Images/test.png">';
var tmp = document.createElement('div');
tmp.innerHTML = str;
var alt = tmp.getElementsByTagName('img')[0].alt;
If you must use jQuery (or just prefer it) then the other answer provided by Alexander and Ashivard will work.
Note: My answer was provided for completeness and more options. I realize the OP asked for jQuery solution and not native js.
Being $a your <a/> element.
Using jQuery you can do:
$("img", $a).first().attr("alt");
Or, using pure JavaScript:
var $img = $a.getElementsByTagName("img")[0];
console.log($img.alt);
​
See it here.
use this.
var altName=$('a img').attr('alt');

Javascript function innerHTML not styled correctly

I'm trying to update some HTML using javascript in a webapp that uses JQuery mobile.
For some reason, I can not use the innerHTML attribute to create a JQuery Mobile button.
For example:
document.getElementById('someDiv').innerHTML = document.getElementById('someDiv').innerHTML + '<p><em>' + var1 + '</em>:<br />' + var2+'</p>';
works and gets styled correctly but:
document.getElementById('someDiv').innerHTML = document.getElementById('someDiv').innerHTML + '' + var1 + '';
does not. I should say that the someDiv is enclosed within a <div data-role="controlgroup"> if that would make any difference. Also, there are other buttons on the page that work fine.
Why doesn't this work and how can I make it work?
EDIT: I am compiling this into a native app using PhoneGap if that makes any difference...
You need to trigger the pageCreate event so that jQuery Mobile knows to re-style the element that you just added.
$("#someDiv").trigger("create")
When adding elements that have special functionality, it is important to re-run the initialisation of said functionality.
For this purpose, I like to define a dom_mods() function that does exactly that. So, whenever I add content to the page, I simply call dom_mods() and all my special features are run or updated.
It looks like you're trying to append an element to the div.
var div = document.getElementById('someDiv'),
anchor = document.createElement('a');
anchor.setAttribute('href', '#');
anchor.addEventListener('click', appendButton, false);
anchor.setAttribute('data-role', 'button');
anchor.innerHTML = var1;
div.appendChild(anchor);
Let me know if you have any questions.

Insert HTML as a String, without JQuery

I'm looking for a method to insert a string, which contains HTML data, into a div element.
The string is loaded via XHR, and there is no way of knowing what elements and such are in it.
I've searched around for a bit, and found some things that might help, but wouldn't completely work for me. What I need is something similar to the update() function from the Prototype framework:
http://prototypejs.org/api/element/update
The platform I'm writing for does not allow frameworks to be used, or JQuery. I'm stuck with Javascript. Anyone have any ideas?
I can't use innerHTML, as it does not apply any updates or functions or basically anything that's supposed to occur on load
I have some onload events that need to occur, and as best I know, using innerHTML does not execute onload events. Am I incorrect?
EDIT 2 years later:
For anyone else reading, I had some serious misconceptions about the onload event. I expected that it was a valid event for any element, while it is only valid for the <body/> element. .innerHTML is the proper method to do what I was looking for, and any extra functionality for the elements added, needs to be done manually some other way.
HTMLElement innerHTML Property
The innerHTML property sets or returns the inner HTML of an element.
HTMLElementObject.innerHTML=text
Example: http://jsfiddle.net/xs4Yq/
You can do it in two ways:
var insertText = document.createTextNode(theText);
document.getElementById("#myid").appendChild(insertText);
or
object.innerHTML=text
I'm looking for a method to insert a string, which contains HTML data, into a div element.
What you want to use is the innerHTML property.
Example of use:
<script type="text/javascript">
function changeText(){
document.getElementById('boldStuff').innerHTML = '<p>Universe</p>';
}
</script>
<p>Hello <b id='boldStuff'>World</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
do you mean like this? : http://jsfiddle.net/FgwWk/1 or do you have things in the div already before adding more?
Plain JS.
Just use: element.insertAdjacentHTML(position, text);
position = "beforebegin" | "afterbegin" | "beforeend" | "afterend"
var text = '<a class="btn btn-blue btn-floating waves-effect">\n' +
'<i class="fas fa-user"><span class="badge badge-danger"></span></i>\n' +
'</a>';
var inputPlace = document.getElementById("input-pace");
inputPlace.insertAdjacentHTML("beforeend", text);

.html() and .append() without jQuery

Can anyone tell me how can I use these two functions without using jQuery?
I am using a pre coded application that I cannot use jQuery in, and I need to take HTML from one div, and move it to another using JS.
You can replace
var content = $("#id").html();
with
var content = document.getElementById("id").innerHTML;
and
$("#id").append(element);
with
document.getElementById("id").appendChild(element);
.html(new_html) can be replaced by .innerHTML=new_html
.html() can be replaced by .innerHTML
.append() method has 3 modes:
Appending a jQuery element, which is irrelevant here.
Appending/Moving a dom element.
.append(elem) can be replaced by .appendChild(elem)
Appending an HTML code.
.append(new_html) can be replaced by .innerHTML+=new_html
Examples
var new_html = '<span class="caps">Moshi</span>';
var new_elem = document.createElement('div');
// .html(new_html)
new_elem.innerHTML = new_html;
// .append(html)
new_elem.innerHTML += ' ' + new_html;
// .append(element)
document.querySelector('body').appendChild(new_elem);
Notes
You cannot append <script> tags using innerHTML. You'll have to use appendChild.
If your page is strict xhtml, appending a non strict xhtml will trigger a script error that will break the code. In that case you would want to wrap it with try.
jQuery offers several other, less straightforward shortcuts such as prependTo/appendTo after/before and more.
To copy HTML from one div to another, just use the DOM.
function copyHtml(source, destination) {
var clone = source.ownerDocument === destination.ownerDocument
? source.cloneNode(true)
: destination.ownerDocument.importNode(source, true);
while (clone.firstChild) {
destination.appendChild(clone.firstChild);
}
}
For most apps, inSameDocument is always going to be true, so you can probably elide all the parts that function when it is false. If your app has multiple frames in the same domain interacting via JavaScript, you might want to keep it in.
If you want to replace HTML, you can do it by emptying the target and then copying into it:
function replaceHtml(source, destination) {
while (destination.firstChild) {
destination.removeChild(destination.firstChild);
}
copyHtml(source, destination);
}
Few years late to the party but anyway, here's a solution:
document.getElementById('your-element').innerHTML += "your appended text";
This works just fine for appending html to a dom element.
.html() and .append() are jQuery functions, so without using jQuery you'll probably want to look at document.getElementById("yourDiv").innerHTML
Javascript InnerHTML
Code:
<div id="from">sample text</div>
<div id="to"></div>
<script type="text/javascript">
var fromContent = document.getElementById("from").innerHTML;
document.getElementById("to").innerHTML = fromContent;
</script>

Categories

Resources