find <img> tag inside text string - javascript

I have an xml document (from a feed), which I'm extracting values from:
$(feed_data).find("item").each(function() {
if(count < 3) {
//Pull attributes out of the current item. $(this) is the current item.
var title = $(this).find("title").text();
var link = $(this).find("link").text();
var description = $(this).find("description").text();
Now inside "description" i need to get the img element, but this is causing me some problems. "descripttion" is a regular string element and it seems i can't call the ".find()" method on this, so what do i do?
I have tried calling .find():
var img = $(this).find("description").find("img");
But it's a no go. The img is wrapped in a span, but I can't get to this either. Any suggestions? I'd prefer to avoid substrings and regex solutions, but I'm at a loss.
I've also tried turning the "description" string into an xml object like so:
var parser = new DOMParser();
var desc = parser.parseFromString(test,'text/xml');
$(desc).find("img").each(function() {
alert("something here");
});
But that doesn't work either. It seems like it would, but I get a "document not well formed" error.

Try enclosing the contents of the description tag in a dummy div, that seemed to work better for me, and allowed jQuery's .find() to work as expected.
e.g.
$(feed_data).find("item").each(function() {
if(count < 3) {
//Pull attributes out of the current item. $(this) is the current item.
var title = $(this).find("title").text();
var link = $(this).find("link").text();
var description = '<div>' + $(this).find("description").text() + '</div>';
var image = $(description).find('img');

Hi and thanks for the prompt replies. I gave GregL the tick, as I'm sure his solution would have worked, as the principle is the same as what I ended up with. My solution looks like this:
$(feed_data).find("item").each(function() {
if(count < 3) {
//Pull attributes out of the current item. $(this) is the current item.
var title = $(this).find("title").text();
var link = $(this).find("link").text();
var description = $(this).find("description").text();
var thumbnail = "";
var temp_container = $("<div></div>");
temp_container.html(description);
thumbnail = temp_container.find("img:first").attr("src");
So wrap the string in a div, and then use "find()" to get the first img element. I now have the image source, which can be used as needed.

maybe you should try to convert the description text to html tag and then try to traverse it via jquery
$('<div/>').html($(this).find("description").text()).find('img')
note: not tested

Related

Trying to remove element based on type of attribute

I am trying to remove an element based on type of attribute. It isn't working for some reason.
The element in question is this:
<p style="width:250px;font-size:11px;text-align:left;margin-left:1.2ex;margin-top:0px;margin-bottom:0px;line-height:1.15em;">– in Europe<span style="font-size:8px;"><span style="white-space:nowrap;"> </span></span>(<span style="font-size:9px;">green & dark grey</span>)<br>
– in the European Union<span style="font-size:8px;"><span style="white-space:nowrap;"> </span></span>(<span style="font-size:9px;">green</span>)</p>
I am trying to remove it this way - item is a container element.
$(item).find("p").filter("[style]").remove();
There are no other <p> tags with the attribute style, however this doesn't appear to remove it.
Other code, like this, works fine:
$(item).find(".reference").remove();
How do I remove all p tags with the style attribute from the item element?
This is how item is created:
$.get(link, function(response) {
var elements = $.parseHTML(response);
var wiki = $(elements).find('#mw-content-text').find("p");
//var ps = [];
var arrayLength = wiki.length;
for (var i = 0; i < arrayLength; i++) {
if (wiki[i].innerHTML === "") {
break;
}
var item = wiki[i];
The link variable is a link to wikipedia.
Maybe try this:
$.each(item.children('p'), function(index) {
if ($(this).attr('style')) {
$(this).remove();
}
});
item refers to p element itself. you don't have to find p in item:
$(item).filter("[style]").remove();
after re-looking over your question ,
$(item).find("p").filter("[style]").remove();
is perfectly valid , instead of trying to come up with alternative ways to write it , find out what is wrong with item, because it is not what you think it is if above code is not working

setAttribute not working

I am making a plugin for form validation as practice, but for some reason after I create a h2 element and try to set it's attribute, it is not working. Here is the code
var testing = function(regex, value, error_msg, error_msg_field_id){
var pattern = new RegExp(regex);
if (!pattern.test(value)){
var ele = document.createElement("H2");
var node = document.createTextNode(error_msg);
ele.setAttribute('style', 'color:white');
alert("hi");
jQuery(error_msg_field_id).append(node);
}
}
the text appears with no problem, but it is not in white color. This make no sense at all to me
You are using setAttribute correctly, but you are setting the property on your h2-element, which is never actually inserted in your DOM.
You can change and simplify the relevant section of your code to:
var ele = document.createElement("H2");
ele.textContent = error_msg;
ele.setAttribute('style', 'color:white');
jQuery(error_msg_field_id).append(ele);
The usage of jQuery here is also not necessary. You can simply use
document.querySelector("#" + error_msg_field_id).appendChild(ele);
which is equally simple.

Parse a string in jquery, change something and get the modified string back

I have a string containing html code, something like this: http://jsbin.com/ocoteg/1.
I want to parse this string, make some changes (just for example: change all links to a span), and then get the modified html string back.
Here is a jsbin, where I started this, but I can't make it work: http://jsbin.com/okireb/1/edit.
I get the html string, I parse it with jquery, but I can't replace the links, and get the modified html string back.
UPDATE
Why the downvote? What is the problem with this question?
You can do it in a loop also
dom.each(function(i,v){
if(v.tagName == "A"){
dom[i] = $('<span/>').html($(v).html())[0]; // replace it right away with new span element
}
});
var newString = $('<div>').append(dom.clone()).html(); //<-- to get new string http://stackoverflow.com/a/652771/1385672
console.log(newString);​
EDIT:
Here's how you can do it keeping the other tags
var dom = $(text.split('\n'));
$(dom).each(function(i,v){
var ele = $(v)[0];
if($(ele).is('a')){
dom[i] = $('<div>').append($('<span/>').html($(v).html())).html();
}
});
var newString = dom.get().join('\n');
http://jsbin.com/okireb/32/edit
Use find instead of filter :
var dom = $('<div>'+text+'</div>');
dom.find('a').each(function() {
var el = $(this);
var html = el.html();
var span = $('<span/>').html(html);
el.replaceWith(span);
});
console.log(dom.children()); ​
Note that I wrap everything for the case where the initial dom isn't one element.
Demonstration
To get the html back as a string use
var html = dom.html();
This should be what you want (can be improved)
var text = '<!DOCTYPE html><html><head><meta charset=utf-8 /><title>JS Bin</title></head><body>Link 1Link 2Link 3</body></html>';
var body_content = text.substring(text.indexOf('<body>') + 6, text.indexOf('</body>'));
var $dom = $('<div/>').html(body_content);
$('a', $dom).each(function() {
$('<span>' + $(this).html() + '</span>').insertAfter($(this));
$(this).remove();
});
var text_new = text.replace(body_content, $dom.html());
// text_new contains the entire HTML document with the links changed into spans
You could do it with .replace.
Probably not the nicest way of doing it though.
dom = dom.replace(/<a /g,'<span');
dom = dom.replace(/<\/a>/g,'</span>');
Demo: http://jsbin.com/okireb/14/edit

Add a js function to the DOM?

I have a very simple HTML page. After everything is loaded, the user can interact with it perfectly. Now, at some point, the user clicks on an element. An ajax call is made and new data is being requested. I now want to remove the previous element the user clicked on with the element(s) the user has requested (on the same page) - practically remove the old element from the DOM and add the new one. Well, I did this as well, but I am unable to add a function to the newly created element. This is my function:
setCountry = function(value){
document.getElementById('country').innerHTML = value;
}
and I'm trying to add it like this to my element
a_tag.setAttribute("href", "javascript:setCountry(countries[i]);");
The function is being called and writes "undefined" to the innerHTML element. I set the attribute using a for loop and just above the for loop I alert an element from the array to be sure it's correct, and it prints out the correct value.
I assume the problem happens because the function is being created on the first load of the DOM, but I'm not sure. Can anyone shed some light on what is really happening here and what I should do to correct it? I want to be able to add more functions so not looking for a work around writing an innerHTML tag, I just want to understand what I'm doing wrong.
Thank you.
Edited with more code
//declare an array to hold all countries form the db
var countries = new Array();
function getCountries(region) {
document.getElementById('scroller').innerHTML = '';
//send the data to the server and retreive a list of all the countries based on the current region
$.ajax({
type: "POST",
url: "scripts/get_countries.php",
data: {
region: region
},
success: saveDataToArray,
async: false,
dataType: 'json'
});
//save the data to an array
function saveDataToArray(data){
var i = 0;
while (data[i]){
countries[i] = data[i];
i++;
}
}
scroller = document.getElementById('scroller');
//create a ul element
var holder = document.createElement("ul");
//here create a back button which will recreate the whole list of regions
var total = countries.length;
for(i=0;i<total;i++){
//create the first field in the list
var bullet_item = document.createElement("li");
//create an a tag for the element
var a_tag = document.createElement("a");
//set the redirect of the tag
a_tag.setAttribute("href", "javascript:setCountry(this);");
//create some text for the a_tag
var bullet_text = document.createTextNode(countries[i]);
//apend the text to the correct element
a_tag.appendChild(bullet_text);
//apend the a_tag to the li element
bullet_item.appendChild(a_tag);
//apend the item to the list
holder.appendChild(bullet_item);
}
//apend the holder to the scroller
scroller.appendChild(holder);
}
function setRegion(region){
document.getElementById('region').innerHTML = region;
}
setCountry = function(value){
document.getElementById('country').innerHTML = value;
}
There is no need for quoting the code in a string. Instead of this:
a_tag.setAttribute("href", "javascript:...")
Try to form a closure:
a_tag.onclick = function () { ... }
Note that by default <A> elements without HREF do not look normal, but you can fix that with CSS.
Problem solved
Everything was good apart from the way I was declaring the href parameter
a_tag.setAttribute("href", "javascript:setCountry("+'"'+countries[i]+'"'+")");
it's all the usual, a game of single quotes and double quotes.
Thanks everyone for pitching in ideas. Much appreciated as usual
Adrian

Access a label's attribute using jquery

I have some data coming from the server in which I fill A Div in the Html page with.
The way I write the div is as follows:
<div class="BigDiv"><label class = "AttList" Std_Id="' + Std_Id + '">' + Std_Name +'</label></div>
Now, I want the data inside this div.
There are some other labels inside the div so I use this.children to access this label.
var labels = $(this).children('div');
var StdName = this.children[0].childNodes[0].nodeValue;
I want to access the Std_Id inside the Std_Id attribute, but I don't know how to do it ... Do you have any ideas?
Thanks.
Assuming that $(this) is a reference to the .BigDiv element:
var StdName = $(this).find('label').attr('Std_Id');
Or, similarly, and with the assumption that this is the .BigDiv element:
var children = this.childNodes;
for (var i=0,len=children.length; i<len; i++){
if (children[i].nodeType == 1 && children[i].tagName.toLowerCase() == 'label'){
var StdName = this.getAttribute('Std_Id');
}
}
References:
jQuery:
attr().
find().
JavaScript
element.getAttribute().
node.nodeType.
tagName.
toLowerCase().
Use getAttribute:
var labels = $(this).children('div');
var StdId = this.children[0].getAttribute("Std_Id");
Note that, according to the HTML5 spec, custom attributes should start with data-, though most browsers can tolerate it.
To save elements, which were selected using a jQuery-Selector, do this:
$labels = $('.BigDiv').find('label');
Now you can loop through each label with jQuery's foreach loop:
$.each($labels, function() {
var std_id = $(this).attr('Std_Id');
// do something with std_id
});
You could use the attr method as such,
var value = $('.AttList').attr('Std_Id');
EDIT
OK, so you for your implementation, you need to do this...
var value = $(this).find('.AttList').attr('Std_Id');
Assuming that this is the div or the parent of that div

Categories