I have a link like :
<a rel="Test Images" class="thickbox preview_link" href="http://www.localhost.com:8080/testwp/wp-content/uploads/2013/12/2013-10-02_1728.png">
i need to get the url of that image inside a javascript file loaded on the same page.
i tried something like:
image_src = jQuery('a[class=thickbox preview_link]').attr('href');
but all i get is Uncaught Error: Syntax error, unrecognized expression: a[class=thickbox preview_link] in the console.
i am using jquery 1.10.2 on the site
You would do:
jQuery('a.thickbox.preview_link').attr('href');
Your attribute selector syntax is incorrect since it has space you need to wrap them in quotes ('a[class="thickbox preview_link"]'), but you can always use class selector which would be mostly faster than the attribute selector and the order doesn't matter as well.
Just in case you need it, here's the vanilla Javascript version
Get the image(s)
var image = document.getElementsByClassName('thickbox preview_link');
Getting the href (of the first image)
var image_href = image[0].getAttribute('href');
Better version
// Declare the image_href variable
var image_href;
// Getting a nodeList of all the applicable images
var image = document.getElementsByClassName('thickbox preview_link');
// If there's only 1 image and/or you only want the first one's href
if(image[0] !== undefined) {
// if condition to check whether or not the DOM has the images in the first place
// if yes, update the image_href variable with the href attribute
image_href = image[0].getAttribute('href');
}
Best of luck!
thickbox preview_link is actually 2 class tokens, so you're looking for a.thickbox.preview_link or (for that specific attribute) a[class="thickbox preview_link"] (notice the quotes)
image_src = jQuery('a.thickbox.preview_link').attr('href');
// or
image_src = jQuery('a[class="thickbox preview_link"]').attr('href');
Related
I am trying to get the value of the backgound-image url. The url is set inline directly in the element tag with the style attribute like so
<a style="background-image: url(https:// ....)"></a>
I tried doing
var url = $(this).css('background-image')
with various regexes but it does not seem to work. I am trying to store this URL into MongoDB but I get this error
var styles = parse(el.attribs.style);
TypeError: Cannot read property 'attribs' of undefined
Get the style value, then strip the URL from it
var bi = $('a').css("background-image");
alert(bi.split(/"/)[1]);
The call to jQuery .css("background-image") always returns the URL within double quotes, regardless how it was set originally.
Sample fiddle:
https://jsfiddle.net/6qk3ufcb/
In vanilla JS, having full DOM access, it can be done like so:
document.querySelector('a').style.backgroundImage.split('"')[1]
Or, if for whatever reason you don't have DOM access (for example dealing in node, and operating on some simplified HTML parser) it can also be done with regexp:
const htmlString = `<div class="bg-div" style="background-image: url('https://loremipsum.com/imageIpsum.jpg');">`
const reg = /url.'([\w\W]+?)'/;
const searched = reg.exec(htmlString)
console.log(searched[1]) //=> https://loremipsum.com/imageIpsum.jpg
var strHTML = "<div><img src='/fake/path/fakeImage.jpg'/><span id='target'>text to extract</span></div>";
var dom = $(strHTML);
var extractedText = dom.find("#target").text();
alert(extractedText);
When I convert the HTML string to a jQuery object, jQuery makes GET request to retrieve pictures as you can see in the network tab in the developer tools.
JsFiddle
How can I convert a HTML string to jQuery object without downloading any resources from the parsed string ?
Note : jQuery.parseHTML does not return a jQuery object, you cannot use .find() for example.
I don't think this is possible, since its not jQuery (or javascript) that does the image loading but the browser - as soon as a src attribute is set on an img element the browser will attempt to download it.
One thing you can do is change the element name from img to something else before building the dom, or change the src attribute to something else, for example:
// change the <img> elements to <my_img> to avoid image fetching
strHtml = strHtml.replace(/<img /gi, "<my_img ").replace(/<\/img>/gi, "</my_img>");
// or the 2nd alternative: change the src attribute of images
strHtml = strHtml.replace(/<img([^>]*?) src=/gi, "<img$1 my_src=")
// now its safe to parse into DOM - no images will be fetched
var dom = $(strHtml);
note this simple "search and replace" may replace texts other than the elements you want, but it may be sufficient for your use case.
You can feed it through $.parseXML first:
var strHTML = "<div><img src='/fake/path/fakeImage.jpg'/><span id='target'>text to extract</span></div>";
var dom = $($.parseXML(strHTML));
var extractedText = dom.find("#target").text();
alert(extractedText);
I don't know if it is answered already before. I don't know what to search for.
All I want to know is if there is a jquery function for the following problem.
Let's say I have an URL string like this - www.example.com/a/b/../c
I want to get www.example.com/a/c
One simple way is to create a link element, set its href property, and then read it.
var a = document.createElement("a");
a.href = "http://www.example.com/a/b/../c";
var resolved = a.href;
console.log(resolved); // "http://www.example.com/a/c"
Or using some jQuery:
var resolved = $("<a>").prop("href", "http://www.example.com/a/b/../c").prop("href");
console.log(resolved); // "http://www.example.com/a/c"
Live Example
This works relative to the current document's path, although with the URL above it doesn't matter as the URL is absolute.
Note that it's important that we're using the reflected property, not the attribute, here.
This is my first time working with .addClass().
In my project, I need to display notifications on a dummy phone screen (an image of iPhone). A notification has a title and some description. This title and description is coming from a form on the same webpage. To compose this notification, I am doing:
var notificationText = $('#title').val().addClass('title') + plainText.addClass("description");
However, I am getting an error:
TypeError: $(...).val(...).addClass is not a function
What am I doing wrong here?
UPDATE:
So, as per the overwhelming requests, I did:
var notificationText = $('#title').addClass('title').val() + plainText.addClass("description");
However, I am getting an error:
Uncaught TypeError: Object sss has no method 'addClass'
jsFiddle
UPDATE 2: I do not need to style the description, so I removed the class related to it. Please see my updated fiddle. Now the problem is that the text in title is getting bold instead of the one copied in #notifications. It is not getting styled as per the CSS.
So many answers in so little time... sigh
I gathered what I think you wanted. Try this one:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/7b3j2/13/
$(document).ready(function(){
CKEDITOR.replace( 'description' );
$('#title').focus();
$('form').submit(function(event){
event.preventDefault();
var html=CKEDITOR.instances.description.getSnapshot();
var divEle=document.createElement("DIV");
divEle.innerHTML=html;
var plainText=(divEle.textContent || divEle.innerText);
var $title = $('<span></span');
$title.addClass('title');
$title.text($('#title').val());
var $desc = $('<span></span');
$desc.addClass('description');
$desc.text(plainText);
$('form').append($title);
$('form').append($desc);
});
});
You can obviously chain some of the span operations, but I left them readable for now. Shorter version would look like:
var $title = $('<span></span').addClass('title').text($('#title').val());
var $desc = $('<span></span').addClass('description').text(plainText);
$('form').append($title).append($desc);
As you probably know by now, but for completeness, the initial errors were the result of trying to apply jQuery methods to string objects. This solution creates new jQuery span objects that can then be styled and appended to the form.
You are trying add class to a value, which is definitely is not a jQuery object
Try this instead:
$('#title').addClass('title').val()
addClass can only be performed on jQuery objects and returns a jQuery object - that's what makes it chainable. You can't add a class to a string.
So, in this code, there are actually two mistakes:
1) plainText.addClass - plainText is a string, and not a jQuery object. You must add the class to the element you created (in your case, the divEle element), but, since addClass only works with jQuery objects, you must convert your div to a jQuery element first. You can accomplish this by doing the following:
$(divEle).addClass('description');
2) addClass returns a jQuery object, so you can't concatenate it with a string.
EDIT: Just realized that you're appending notificationText (which is a string) to the DOM. You must convert it to a div and add the div to the DOM.
jsFiddle: http://jsfiddle.net/7b3j2/17/
Mistake done by you:
<div id="title"><div>
$('#title').val().addClass('title')
->Now here $('#title').val() will give that particular element value.
->$('#title').val().addClass() you are adding class to that value.
Use this:
$('#title').addClass();
As you cannot add class to element's value.
You should addClass to particular element as addClass internally will add attribute class to that element.
So finally solution becomes:
$('#title').addClass('title').val()
For adding a class, you have to use
$('#title').addClass('title');
If you want to get the value, you can use
$('#title').addClass('title').val()
While addClass and val() are both methods on the jQuery object, val() is not chainable like addClass is. When you do $('#title').val() you aren't returning the object, you're only returning the string value of the element.
Use this instead:
$('#title').addClass('title');
And if you still need to get the value:
$('#title').addClass('title').val();
The reason why plaintext is producing an error is because you're trying to use the jQuery addClass method on a DOM node that has been natively created with document.createElement("DIV");. This will not work. To get it to work you either need to to define your new element with jQuery:
var divEle = $('<div></div>');
and then add the class:
divEle.addClass('description');
Or use the native classname method to add the class to the DOM node:
divEle.className = divEle.className + " description";
Try putting addClass first
$('#title').addClass('title');
Update
To get the code fully working you should split up the line like so.
var notificationText = $('#title').val() + ' ' + plainText;
$('#title').addClass('title');
$(plainText).addClass("description");
Fiddle
Final Update
So what we actually want to do here is:
get the values of the content
append them on submit and style the appended text
Example
// Get the text.
var notificationText = $('#title').val() + ' ' + plainText;
// Append to form.
$('form').append('<span class="summary">' + notificationText + '</span>');
// CSS styling
.summary {
display:block;
font-weight: bold;
}
See Fiddle
Considering #title is the id of the element.
You can directly need to add classname to it.
$('#title').addClass('className');
where className is the name of the class.
because you are trying to add class over value instead of element.
$('#title').val().addClass('title') //it is wrong
replace it with:
$('#title').addClass('title')
if plainText is not an element object you initialize by
var plainText = $('#anotherId');
will also cause this error.
Here I have get one error in JavaScript div_element is null or not an object.
I have given my code below:
function showLoading(id) {
div_element = $("div#" + id)[0];
div_element.innerHTML = loading_anim; // Error in this line
}
When I am debugging my script but it's working fine in other browsers including IE 8, but it's not working in IE 7. I don't understand what exact issue occur in this script.
First of all, you dont need to put a tag name infront of the jQuery, unless you have other elements with exact same id on other elements, in other pages.
Next, your statement div_element.innerHTML = loading_anim; is correct. So, the only explanation is that, there is no element with that ID, in the DOM.
Finally, since you are usign jQuery already, no need to mix up native JS and jQuery to create a dirty looking code.
function showLoading(id) {
div_element = $("#" + id);
console.log(div_element); //check the console to see if it return any element or not
div_element.html(loading_anim);
}
I think you don't select anything with your jquery selector (line 2)
try to display
id
"div#" + id
$("div#" + id)
$("div#" + id)[0]
You can use firebug javascript console or a simple alert like this:
alert($("div#" + id)[0]);
And see if you must id or class on your div ( use # or . selector)
I suppose, that nic wants to display some loader GIF animation, I confirm, that nic must use jQuery .html() method for DOM objects, and tusar solution works fine on IE6+ browsers. Also (it is obvious but anyway) nic must assign a value to loading_anim variable in script, lets say: var loading_anim = $('#loader').html(); before assigning its value to div_element.
Use .html() for jQuery objects. innerHTML work for dom objects, they wont work for jQuery objects.
function showLoading(id) {
div_element = $("div#" + id);
$(div_element).html(loading_anim); // Provided `loading_anim` is valid html element
}