Get link name in javascript - javascript

Example
Example Name
I would like to get "Example Name"
I know I can do this with regex, but I'm looking for a simpler, faster approach. The closest I came was with Jquery using the .attr("href") attribute. I tried putting .attr("title"), but that doesn't work since I technically don't have a title there.

.text()

Try this
var t = $('a').text();
alert(t);
http://jsfiddle.net/jasongennaro/gZsbW/
Of course, this targets the first link it encounters. Better if you can hook it to an ID.
Example
Example Name
Then
var t = $('#linkName').text();

You can use something like this, which works in regular Javascript...
This has the advantage that it will extract the text from things like:
This is a <i>link</i> with <b>markup</b>
var getText = function(el) {
var ret;
var txt = [],i=0;
if (!el) {
ret = "";
} else if (el.nodeType === 3) {
// No problem if it's a text node
ret = el.nodeValue;
} else {
// If there is more to it, then let's gather it all.
while(el.childNodes[i]) {
txt[txt.length] = self.getText(el.childNodes[i]);
i++;
}
// return the array as a string
ret = txt.join("");
}
return ret;
};

Try var LinkName = document.links.text;
Or for IE you will need var LinkName = document.links.innerText

Related

if statement inside jQuery selector

I'm getting those 2 vars from the DOM:
var get_category = $('#category').find('.current').attr('rel');
var get_subcategory = $('#subcategory').find('.current').attr('rel');
and I want here to find the classes in my DOM and show it
$('.filter-result').find('.'+get_category, '.'+get_subcategory ).show();
But I need to write it inside the .find() only if the variables are exist
I hope it answers your question:
var get_category = $('#category').find('.current').attr('rel');
var get_subcategory = $('#subcategory').find('.current').attr('rel');
var classes = [];
if (get_category) {
classes.push('.' + get_category);
}
if (get_subcategory) {
classes.push('.' + get_subcategory);
}
//if get_category or get_subcategory were found
if (classes.length) {
$('.filter-result').find(classes.join('')).show();
}
I do like Gabriels answer because it is very simple another option that works well and is extensible all you would have to do add another selector is add it to the selectors array. It is a little bit more advanced using javascripts filter and map array methods though.
var get_category = $('#category').find('.current').attr('rel');
var get_subcategory = $('#subcategory').find('.current').attr('rel');
var selectors = [get_category, get_subcategory];
var query = selectors.filter(function(elem) {
if (elem) { return elem };
}).map(function(elem){
return '.' + elem;
}).join(', ')
$('.filter-result').find(query).show();

InDesign Target XML Structure element by partial name

In my Structure pane there are some elements that their partial name is identical, eg. image01, image03, image03 etc.
I want to know if there is a way to access them via scripting using the itemByName() method, but by providing a partial name, like in CSS i can use
h1[rel*="external"]
Is there a similar way to do this in:
var items2 = items.xmlElements.itemByName("image");
You could try something like the code below. You can test against the markupTag.name properties with a regular expression. The regex is equivalent to something like /^image/ in your example (find image at the beginning of a string).
function itemsWithPartialName(item, partialName) {
var elems = item.xmlElements;
var result = [];
for (var i=0; i<elems.length; i++) {
var elem = elems[i];
var elemName = elem.markupTag.name;
var regex = new RegExp("^" + partialName);
if (regex.test(elemName)) {
result.push(elem);
}
}
return result;
}
itemsWithPartialName(/* some xml item */, 'image');
You can use an XPath:
var rootXE = app.activeDocument.xmlElements.item(0);
var tagXEs = rootXE.evaluateXPathExpression("//*[starts-with(local-name(),'image')]");

jQuery append element if it doesn't exist, otherwise replace

Here's a short piece of code:
var $el = $("#something").find(".test");
if (!$el.length) {
$("#something").append('<div class="test">somecontent</div>');
} else {
$el.replaceWith('<div class="test">somenewcontent</div>');
}
I couldn't find a method appendOrReplaceWith or anything similar.
Any ideas how can I make it shorter?
I believe that:
$("#something").appendOrReplace('<div class="test">sometext</div>');
would be much easier to read, but no such method is available yet.
Just remove it first then append.
$(".test").remove();
$("#something").append('<div class="test">somecontent</div>');
Mandatory vanilla answer. It may not be shorter, but it's faster.
Get the element, grab all subelements with the class "test", create your div, check the subelements length, and if length is truthy, set the innerHTML to the div. Else, append it.
var el = document.getElementById("something");
var subel = el.getElementsByClassName("test");
var div = document.createElement("div");
div.className = "test"
if (subel.length) {
div.textContent = "somenewcontent";
while(el.hasChildNodes()) el.removeChild(el.lastChild); //remove child nodes
el.appendChild(div);
} else {
div.textContent = "somecontent";
el.appendChild(div);
}
Adding a method like findOrAppend to jQuery could be useful:
$.fn.findOrAppend = function(selector, content) {
var elements = this.find(selector);
return elements.length ? elements : $(content).appendTo(this);
}
Then you can chain text, replaceWith, empty etc. as needed:
$("#something")
.findOrAppend(".test", "<div class='test'>")
.text("newcontent");
First of all you should cache your selectors:
var $som = $('#something');
var $ele = $(".test",$som);
var newHtml = '<div class="test">somecontent</div>';
if (!$el[0]) $som.append( newHtml );
else $ele.replaceWith( newHtml );
but you already did it really fine, (beside not caching repeated selectors), and me, trying to make it smaller could be a**-kicked for not using {} for my if and else :)
I would do this
var $s = $("#something"), $t = $s.find(".test"), c = 'New content';
( $t[0] ? $t:$s)[( $t[0] ? 'html':'append')](( $t[0] ? c :$('<div>',{class:'test'}).append(c)));

Remove character from div id

I need to remove the tag within this div id. What am I doing wrong here?
function thanksForHelping(div){
var siblingOne = $(div).next();
var siblingTwo = $(div).next().next();
var NIDsiblingOne = siblingOne.substring(1);
var NIDsiblingTwo = siblingTwo.substring(1);
}
I want to see:
siblingOne == #yo
siblingTwo == #hi
NIDsiblingOne == yo
NIDsiblingTwo == hi
However I am receiving this error in my console:
TypeError: siblingOne.substring is not a function
.next() returns a jQuery object (docs), which is why you cannot call substring() on it. If you want the id, you need to use attr() or prop():
$(div).next().attr('id'); // or prop()
although it's a little unclear exactly what you're going for, but hopefully this should point you in the right direction.
It looks like you're saying you have some div like <div id="#myid"> This is incorrect. You shouldn't have the # in the id; that's just how it's referenced in CSS queries.
But, you could be using links to link to that div like this: <a href="#myid"> in which case you would want to strip the # to get the proper value if you were going to target with something like getElementById()
Even so, you're calling substring on a jQuery object, not on the id itself. Try something like:
function thanksForHelping(div){
var siblingOne = $(div).next(), siblingTwo = siblingOne.next();
var existingIdOne = siblingOne.attr("id");
var existingIdTwo = siblingTwo.attr("id");
var noHashIdOne = existingIdOne.replace(/^#/, ''); //Using regex here in case it doesn't actually have a leading #
var noHashIdTwo = existingIdOne.replace(/^#/, '');
}
If you were doing the link thing that I mentioned before, you'd have two ways to approach it: 1) Fetch the actual id like I show above, or use jQuery and just use the version with the hash. So, something like this:
function elementsForIntraPageLinks(){
var links = $("a.internal");
links.each(function(i, link) {
var href = link.href;
var targetElement = $(href);
console.log("targetElement:", targetElement);
});
}
or without jQuery but in a modern browser:
function elementsForIntraPageLinks(){
var links = document.querySelectorAll('a[href^="#"]');
links.forEach(function(link, i, links) {
console.log("targetElement:", document.querySelector(link.href));
});
}
or in a slightly older browser
function elementsForIntraPageLinks(){
var links = document.getElementsByTagName('a'), i, ii, link;
for(i = 0, ii = links.length; i < ii; i++){
link = links[i];
if (/^#/.test(link.href)) {
console.log("targetedElement", document.getElementById(link.href.replace(/^#/, ""));
}
});
}

Create Element in Jquery

I would like to create element in Jquery/Javascript by using "div.someelement" like this
var SomeElement = $("div.someelement");
$( "#container" ).append( SomeElement );
But I don't want to copy element with the same class, I would like to create new one.
document.createElement is creating "<div.somelement>" instead of <div class="someelement">
I would use the following method to create elements on the fly
$("<div/>",{
"class" : "someelement",
// .. you can go on and add properties
"css" : {
"color" : "red"
},
"click" : function(){
alert("you just clicked me!!");
},
"data" : {
"foo" : "bar"
}
}).appendTo("#container");
Try this:
var $someelement = $('<div class="someelement"/>').appendTo('#container');
This will create a brand new element inside of #container and save it as $someelement for easy reference later.
http://api.jquery.com/jQuery/#jQuery2
UPDATE
You could clone the original then empty it out. This doesn't affect the original element at all.
var $someelement = $('div.someelement').clone().empty().appendTo('#container');
You can do this by the following:
var newElement = $('<div class="someelement"></div>');
$('#container').append(newElement);
or if you don't need the element you can directly append it:
$('#container').append('<div class="someelement"></div>');
According to the question you want to use a syntax like "div.someelement" to create an element.
In order to do that, you need to make your own parser.
It is very simple if that will be the exact syntax.
var str = "div.someelement",
parts = str.split("."),
elem = $("<" + parts.shift() + ">"),
cls;
while (cls = parts.shift())
elem.addClass(cls);
But if you're going to do this, you might as well use native methods.
var str = "div.someelement",
parts = str.split("."),
elem = document.createElement(parts.shift());
elem.className = parts.join(" ");
If you want to allow for full CSS syntax for creating an element, then you may want to look at the regex parser that Sizzle uses, and use it for your needs.
Use this:
var someElement = $("<div></div>");
someElement.addClass("someelement");
$("#container").append(someElement);
Or you can chain together the calls:
$("#container").append(
$("<div></div>")
.addClass("someelement")
);
EDIT:
Perhaps I misunderstood the question, maybe this will help. To create a new set of elements, use jQuery's clone method:
$("div.someelement").clone().appendTo("#container");
I would use zen coding for textarea as a starting point. Its syntax is close enough for what you are trying to do, its a well understood implementation. You should be able to invoke the transformation from a raw string rather than from a textarea with a little tweaking.
Since you are asking about creating an element from css syntax, you need to use a parser to interpret the syntax.
Here is an example you can build from. This will match an element name followed by id, class or other attributes. It won't cover some edge cases, but will work in most cases.
var elem_regex = /^(\w+)?|(#|\.)([^.#\[]+)|(\[[^\]]+?\])/g
Then make a function to get the parts and create an element.
function elementFromSelector(str) {
var match, parts = {}, quote_re = /^("|').+(\1)$/;
while (match = elem_regex.exec(str)) {
if (match[1])
parts.name = match[1];
else if (match[2] === ".") {
if (!parts.clss)
parts.clss = [];
parts.clss.push(match[3]);
} else if (match[2] === "#")
parts.id = match[3];
else if (match[4]) {
var attr_parts = match[4].slice(1,-1).split("="),
val = attr_parts.slice(1).join("");
parts[attr_parts[0]] = quote_re.test(val) ? val.slice(1,-1) : val;
}
else throw "Unknown match";
}
if (parts.name) {
var elem = document.createElement(parts.name);
delete parts.name;
for (var p in parts)
if (p === "clss")
elem.className = parts[p].join(" ");
else
elem[p] = parts[p];
return elem;
} else throw "No element name at beginning of string";
}
Then pass a proper string to the function, and it will return the element.
var str = 'input#the_id.firstClass.secondClass[type="text"][value="aValue"]';
var element = elementFromSelector(str);
Before creating the element, the parts look like this.
{
"name": "input",
"id": "the_id",
"clss": [
"firstClass",
"secondClass"
],
"type": "text",
"value": "aValue"
}
Then it uses that info to create the element that gets returned.
Simply create a new Element for jQuery:
var $newElement = $(document.createElement("div"));
$newElement.appendTo($("body"));
if you want to at attributes to de element simplie use:
$newElement.attr({
id : "someId",
"class" : "someClass"
});
Rember by class always use like this "class", because class is a reserved name

Categories

Resources