Adding a Values into a div created from document.createElement - javascript

I have a DIV that is created from document.createElement,, I have a few text and a image that needs to be added to this DIV. Could some one suggest me the best way to do it? The image path is given in the image variable. Below is the code that i have already written. contentattachpoint is another DIV that is there in the HTML page which is got by
var contentattachpoint=document.querySelector('.contentattachPoint');
var year="Year of Manufacture:"+arr[i].year;
var power="Engine Power:"+arr[i].power;
var description="Description:"+arr[i].description;
var image=arr[i].image;
var details = document.createElement("div");
details.setAttribute("id", "details");
details.className = "details";
details.value=year+power+description;
contentattachpoint.appendChild(details)
Thanks in advance.

By what I understand of you question I consider that you need text and image both in the div that you created so do something like this
details.innerHTML = description + "<img src='"+image+"'>";

just do what you are already doing use details.appendChild()
Look at this sample example:
just created a demo example to show you how to dynamically create a div and add paragraph tag and image tag to it.
http://jsfiddle.net/2LAYS/2/

If you are using jQuery, use the .append() function.
Example:
$('#details').append('<img src="' + image + '" />');
you should also take a look at Prepend
Source(s)
jQuery API - append()
jQuery API - prepend()

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;

Cannot append image with jquery

I currently have a code working where i can add a class based on the url of a page using jquery. However I would like add an image to a div instead of just adding a class. I'm not as proficient in java-script as I could be but I think there is probably a pretty simple solution. The code that doesn't work is
if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
var img = document.createElement("img");
img.src = '~/Content/Images/Template 5A Filmstrip.jpg" />';
}
the code that works right now that I dont want to use is
if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
var $body = $('body');
$body.addClass('campaign');
}
How can apply what I do know that works to what I am trying to get to work?
If for some reason you don't want to use jQuery for this part, you just need to append the element to the body of the html document (or wherever you want it to end up) like so:
Javascript Code
if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
var body = document.getElementsByTagName("BODY")[0];
var img = document.createElement("img");
img.className = 'img-responsive'
img.src = '~/Content/Images/Template 5A Filmstrip.jpg';
body.appendChild(img);
}
You can add a <img> to any element using the jQuery .append() function in the following way:
var imageToAppend = '<img src="http://example.com/img.png" height="200" width="200"/>';
$('#myElementId').append(imageToAppend); //This will append you HTML to the div with id "myElementId"
You can read more about this here: http://api.jquery.com/append/
Happy coding! =]
You should use the element where you need to append (prepend) the image element so the code will look something like:
$("base element selector").append(img);
but you need to consider that the address of the image source may not be correct from the browser point of view - consider the page is hosted in application like http://server.com//applicationgroup/applicationroot/Content/Images/.....jpg may not be pointed with ~/Content/Images/.....jpg you rather need to translate the address to the full server address on the server side.
In my case I just had to remove "~" from:
<img src="~/assets/icons/ic_chevron2.svg" class="rot-90" />
resulting in:
<img src="/assets/icons/ic_chevron2.svg" class="rot-90" />

Variable attributes disapearing when put inside div

Probably a simple question but I can't seem to find the answer. I am dynamically creating a page where I can share twitter links.
var twitter = document.createElement('a');
twitter.setAttribute('href', 'http://twitter.com/share');
twitter.setAttribute('class', 'twitter-share-button twitter-tweet');
twitter.setAttribute('data-text', 'I liked this image');
etc..
I then append it to the div I want such as
$('#doc').append('<img(miscellaneous HTML)>'+twitter)
What I have above works but for CSS formatting purposes I want the image with the twitter share button to be a sub-block. So I create something like this
$('#doc').append('<div id="innerblock'+i+'"><img(miscellaneous HTML)>'+twitter+'</div>)
But when I do this it seems all the attributes of the twitter var are lost, only printing http: // twitter.com/share on the page instead of the button.
I feel it's probably a basic concept I am forgetting.
You are tring to concatenate a DOM object and a String via this code
$('#doc').append('<div id="innerblock'+i+'"><img(miscellaneous HTML)>'+twitter+'</div>)
This twitter variable contains a DOM object and the rest of the append block is String.
Try this:
var div = $('<div id="innerblock'+i+'"><img(miscellaneous HTML)></div>').append(twitter);
$('#doc').append(div);
What I would do is instead of appending the HTML instead you can create the innerblock div and the img tags using document.createElement and append the twitter to the img and the img to the div before appending it all to #doc
You can not concatenate a sting and a DOM node.
var div = $("<div id="innerblock'+i+'">").append("<img />").append(twitter);
or
var div = $("<div/>", {id : "innerblock" + i).append("<img />").append(twitter);
Try substituting .outerHTML String of twitter for DOM element Object twitter ; also adding closing sing quote ' at end of string parameter provided to .append()
var twitter = document.createElement('a');
twitter.setAttribute('href', 'http://twitter.com/share');
twitter.setAttribute('class', 'twitter-share-button twitter-tweet');
twitter.setAttribute('data-text', 'I liked this image');
var i = 0;
$('#doc').append('<div id="innerblock'+i+'"><img />'+twitter.outerHTML+'link</div>')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="doc"></div>

How do I wrap text within a link tag using JavaScript/Jquery?

Here is my current code:
<a class="mg_label_7" href="/" shape="">Hello</a>
I want to have:
<a class="mg_label_7" href="/" shape=""><div id="hello">Hello</div></a>
So I can manipulate the background of the link text without changing the rest of the link areas text. Is there anyway to pinpoint this piece of text and insert a div or even a span using JavaScript/jQuery?
I've been trying to do this for around 3 hours, the closest I've got to achieving it is using
var elem = document.getElementsByTagName('a')[0];
var html = elem.innerHTML;
elem.innerHTML = '<div class="red">'+ html + '</div>'
which successfully targeted a link in my code and changed it to the span, but if I try to getElementsByTagName then getElementByClassName and use mg_label_7 it won't work. There are duplicates of the tag in the code and I want to target all of them.
I'm trying to manipulate a SharePoint web part so I'm not sure if it's stopping it from being edited.
You can use .wrapInner()
$('.mg_label_7').wrapInner('<div id="hello"></div>')

Get src of img element from div?

I want to get the src of the img element in HTML. It looks like this:
<div class="image_wrapper" id="this_one">
<img src="Images/something.jpg" />
</div>
It's very simple when I put an ID in img, and get this src very easy.
But the problem is when I get src of img from div element.
var someimage = document.getElementById('this_one').firstChild.getAttribute("src");
alert(someimage);
I need to get this URL in string. But not worth.
Why not try something like this:
var someimage = document.getElementById('this_one');
var myimg = someimage.getElementsByTagName('img')[0];
var mysrc = myimg.src;
For more on using getElementsByTagName you may want to look at:
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
There is some error checking I didn't do here, but I am just trying to show how you can do it.
Or even simpler :
document.getElementById('yourimageID').getElementsByTagName('img')[0].src
Works for me
The problem is that you have the space characters between the div and img tags. That is why the first element of the div is not the image but the text - which has no method getAttribute.
You can remove spaces and use your js as it was:
<div class="image_wrapper" id="this_one"><img src="Images/something.jpg" /></div>
it will be working:
var someimage = document.getElementById('this_one').firstChild.getAttribute("src");
alert(someimage);
You can get the image tag from your's div using getElementsByTagName('img') as following:
var divEl = document.getElementById('this_one'),
src = divEl.getElementsByTagName('img')[0].src;
The above will solve your task.
More you can get from here Scripting Documents, I advise you to read this chapter.
I know the question is asked for js which has been answered, for jquery
var image = $('#this_one img')[0]; // $('#this_one img') this will return the img array. In order to get the first item use [0]
var imageSrc = image.src;
alert(imageSrc);
It might be useful for someone who looks similarly in jquery.
First, instead of using element.firstChild , use element.children[0] . Also, instead of element.getAttribute('src') , use element.src .
Hope this helps,
Awesomeness01
Why do we need to use jQuery if we can get the img src within the document by querySelector?
Try this:
document.querySelector('[src*="Images/something.jpg"]')
P.S.: jQuery has 94 kb minified file size. Please don't include it unless there's a requirement.

Categories

Resources