I'm trying to write a Greasemonkey script. There is something like this in a webpage:
<div id="div1" class="..." title="
asdsadsadasd <e;...
">...</div>
I want to get its title using jQuery attr
method. But it returns an empty value. My js code is like this:
$("#div1").attr("title");
I've tried alert in many different ways and I'm sure that the required element is selected properly and all other attributes are fine! Just this one returns empty string! ( '' ) Does it have something to do with being multiline?
More details: I'm using latest jQuery (1.8.2) and my browser is Firefox 16.0.1. I saw this link and it worked there! So maybe it's because something else. Actually I'm coding in a Greasemonkey script which is altering a webpage that is not mine to edit. So editing the HTML code is not possible.
The title attribute can be used on any HTML element (it will validate on any HTML element.
An element can be identified with a title attribute with xpath or css selector. With the xpath, the expression should be //tagname[@title='value']. In css, the expression should be tagname[title='value'].
HTML title attributes are often perceived as an accessibility (and SEO) bonus, but the opposite is true. For screen reader users the content included inside of the title attribute is typically unnecessary, redundant, and possibly not even used.
title
isn't a valid attribute for div, but should still work. If you can change the html easily you could use:
<div id="div1" class="..." data-title="
asdsadsadasd <e;...
">...</div>
JS
alert( $("#div1").data("title"));
Also make sure you are wrapping code in document.ready
so element exists when code fires. I suspect this may be your problem
$(function(){
/* your code*/
})
The title
is blank because it (or most likely the <div>
) is added via AJAX, after the Greasemonkey script fires.
Use the waitForKeyElements() utility to handle this kind of situation.
Here is a complete script that uses jQuery and waitForKeyElements
to grab that title:
// ==UserScript==
// @name _Grab element's title, when it is added by AJAX
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change introduced
in GM 1.0. It restores the sandbox.
*/
function grabDivTitle (jNode) {
//***** YOUR CODE HERE *****
var titleStr = jNode.attr ("title");
console.log ("Title is:", titleStr);
}
waitForKeyElements ("#div1", grabDivTitle);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With