Frage

Is there a jQuery selector that will get the content of an element's attribute, but if the attribute is empty, it will get the content of the element itself? For example, say I have the following HTML:

<h2 alt="apple">Hello, world</h1>
<h2>banana</h2>

Essentially, I want it to do something like "h2.alt|h2" (so, if no "alt" tag, select the element itself).

In this example, I want to be able to get the following in a list:

apple
banana

The reason for this is that I will be using a jQuery ToC plugin that allows you to give it jQuery selectors for which elements to pull the ToC from (e.g. "h1,h2,h3"). I want to be able to specify in some of my elements an alternate attribute if I want the ToC text to be different from the content/header text.

Any help would be great!

Thanks!

EDIT:

Just to clarify - it would have to be a selector, because it's something that I have to pass into the plugin. (Such as "h2.alt,h3,h4.alt|h4"). It can't be actual code.

Thanks!

War es hilfreich?

Lösung

Here's the FIDDLE

$('h2').each(function (id, value) {
    var altAttr = $(this).attr('alt');
    if (altAttr === undefined) alert($(this).text());
    else alert(altAttr);
});

Andere Tipps

You can

var results = $('h2').map(function(){
    var $this = $(this), alt = $this.attr('alt')
    return alt  == undefined ? $(this).text() : alt 
}).get();

Demo: Fiddle

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top